diff --git a/HANDOFF.md b/HANDOFF.md index 5fd12d6..50f4a45 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -13,6 +13,9 @@ - 已通过五项边界测试:匿名及非管理员拒绝、管理员页面可读、写请求来源校验、路径穿越和符号链接越界拒绝、系统身份拒绝;Python/生命周期脚本语法通过。FPK 构建和实机界面/NTFS 镜像验证正在进行,尚未宣称正式交付。 - 0.1.0 已实际安装并启动:官方网关登录态生效,浏览器可浏览 APFS 目录并显示当前后台任务;Web 进程实际 UID 985(非 root),设备服务为 root,两个 Unix Socket 均为 0660。 - 新版 0.1.1 修正根目录显示、平滑速度/剩余时间估算,并在服务退出时清理应用闲置挂载(不影响正在拷贝的盘)。七项边界测试通过;NTFS 64 MiB 自建镜像只读挂载、1 MiB 文件复制 SHA-256 比对已通过,无实体 NTFS USB 盘测试。0.1.1 待升级并做最终端到端 UI 复制验证。 +- 用户已于本聊天明确同意飞牛的第三方应用免责条款并授权继续更新;0.1.1 已通过网页“手动安装”实际更新。CLI install-fpk 对已有应用只返回 installed,不能用它宣称升级成功;后续更新使用网页手动上传流程,先点“从电脑上传”再选择 FPK。 +- 实机发现网关改写 Host,严格比对 Origin/Host 会拦截合法新建目录请求。0.1.2 改为每次页面实例的私有随机校验值 + 跨站请求限制,并修正非 1000 用户扩展属性归属;相关边界测试和正版网关重写 Host 的正常请求测试通过。0.1.2 待实机更新、实际启动复制与 Release。 +- 比赛目录实际复制已完成:新增 501332211263 字节,数据复制 2197.872 秒;64 个既有文件校验无差异,目录核对无差异,源分区写计数为零、已卸载且恢复原只读标志。目标已 syncfs。脱敏结果见 `verification/2026-11-11-competition-copy.json`。 ## 当前复制任务(2026-11-11 22:36 启动) diff --git a/application/front.py b/application/front.py index 5b88c19..b78d699 100644 --- a/application/front.py +++ b/application/front.py @@ -1,6 +1,8 @@ """Unprivileged HTTP UI, reachable only through the authenticated fnOS gateway.""" import http.server import grp +import hmac +import secrets import json import os from pathlib import Path @@ -11,6 +13,7 @@ import urllib.parse ROOT = Path(__file__).resolve().parent PREFIX = '/app/dayu-diskcopy' VAR = Path(os.environ['TRIM_PKGVAR']) +CSRF_TOKEN = secrets.token_urlsafe(32) class Handler(http.server.BaseHTTPRequestHandler): @@ -34,7 +37,8 @@ class Handler(http.server.BaseHTTPRequestHandler): return self.reply(403, {'error': '请从飞牛桌面使用管理员账号打开此应用'}) path = urllib.parse.urlsplit(self.path).path if path in (PREFIX, PREFIX + '/') and not post: - return self.reply(200, (ROOT / 'index.html').read_bytes(), 'text/html; charset=utf-8') + page = (ROOT / 'index.html').read_bytes().replace(b'__DAYU_CSRF__', CSRF_TOKEN.encode()) + return self.reply(200, page, 'text/html; charset=utf-8') if not path.startswith(PREFIX + '/api/'): return self.reply(404, {'error': '页面不存在'}) action = path.removeprefix(PREFIX + '/api/') @@ -44,11 +48,13 @@ class Handler(http.server.BaseHTTPRequestHandler): if post: if self.headers.get('X-Dayu-Request') != '1': return self.reply(403, {'error': '无效请求来源'}) - origin = self.headers.get('Origin') - if origin and urllib.parse.urlsplit(origin).netloc != self.headers.get('Host'): + # fnOS rewrites upstream Host; validate the private page nonce instead. + if not hmac.compare_digest(self.headers.get('X-Dayu-Token', ''), CSRF_TOKEN): + return self.reply(403, {'error': '页面验证已失效,请刷新应用后重试'}) + if self.headers.get('Sec-Fetch-Site', '') not in ('', 'none', 'same-origin'): return self.reply(403, {'error': '请求来源不匹配'}) length = int(self.headers.get('Content-Length', '0')) - if length > 262144: + if not 0 <= length <= 262144: return self.reply(413, {'error': '请求过大'}) args = json.loads(self.rfile.read(length) or '{}') else: diff --git a/application/index.html b/application/index.html index e2bc45e..b409b6f 100644 --- a/application/index.html +++ b/application/index.html @@ -20,7 +20,7 @@ const states={preflight:'准备中',copying:'正在拷贝',verifying_existing:' function bytes(n){if(!n)return'0 B';const u=['B','KB','MB','GB','TB'],i=Math.min(4,Math.floor(Math.log(n)/Math.log(1000)));return(n/1000**i).toFixed(i>1?1:0)+' '+u[i]} function duration(s){if(s==null)return'估算中';if(s<60)return'不足 1 分钟';if(s<3600)return Math.ceil(s/60)+' 分钟';return Math.floor(s/3600)+' 小时 '+Math.ceil(s%3600/60)+' 分钟'} function error(message){$('error').textContent=message||'';$('error').style.display=message?'block':'none'} -async function api(action,args={},post=false){const url=API+action+(post?'':'?'+new URLSearchParams(args));const r=await fetch(url,{method:post?'POST':'GET',headers:post?{'Content-Type':'application/json','X-Dayu-Request':'1'}:{},body:post?JSON.stringify(args):undefined});const d=await r.json();if(!r.ok)throw Error(d.error||'操作失败');return d} +async function api(action,args={},post=false){const url=API+action+(post?'':'?'+new URLSearchParams(args));const r=await fetch(url,{method:post?'POST':'GET',headers:post?{'Content-Type':'application/json','X-Dayu-Request':'1','X-Dayu-Token':'__DAYU_CSRF__'}:{},body:post?JSON.stringify(args):undefined});const d=await r.json();if(!r.ok)throw Error(d.error||'操作失败');return d} function button(name,fn){const b=document.createElement('button');b.textContent=name;b.onclick=fn;return b} function folderRows(container,entries,source){container.replaceChildren();if(!entries.length){const e=document.createElement('div');e.className='empty';e.textContent=source?'当前目录下没有可选择的文件夹':'当前目录下没有子文件夹,可以直接选作目标';container.append(e);return}for(const entry of entries){const row=document.createElement('div');row.className='row';if(source){const check=document.createElement('input');check.type='checkbox';check.setAttribute('aria-label','选择 '+entry.name);check.checked=selected.has(entry.path);check.onchange=()=>{check.checked?selected.add(entry.path):selected.delete(entry.path);updateSelection()};row.append(check)}const icon=document.createElement('span');icon.className='foldericon';icon.textContent='▰';row.append(icon,button(entry.name,()=>source?browseSource(entry.path):browseDest(entry.path)));const arrow=document.createElement('span');arrow.className='arrow';arrow.textContent='›';row.append(arrow);container.append(row)}} function updateSelection(){$('selection').textContent=selected.size?'已选 '+selected.size+' 个目录。同名文件会先保留,并在复制后校验。':'尚未选择源目录。同名文件会先保留,并在复制后校验。';$('start').disabled=!selected.size||!destPath||busy||loading} diff --git a/packaging/fpk/manifest b/packaging/fpk/manifest index 7301ece..6e9d697 100644 --- a/packaging/fpk/manifest +++ b/packaging/fpk/manifest @@ -1,5 +1,5 @@ appname=dayu-diskcopy -version=0.1.1 +version=0.1.2 display_name=大鱼硬盘拷贝 desc=直接读取 APFS、NTFS 外接硬盘,在飞牛 NAS 本机后台拷贝目录、查看进度和校验结果。 source=thirdparty diff --git a/scripts/save-xattrs.py b/scripts/save-xattrs.py index deb827e..4dc29e1 100644 --- a/scripts/save-xattrs.py +++ b/scripts/save-xattrs.py @@ -13,10 +13,11 @@ import sys def main(): config = json.loads(Path(sys.argv[1]).read_text()) + uid, gid = config.get('uid', 1000), config.get('gid', 1001) source = Path(config['mount']) / config['source_root'] destination = Path(sys.argv[2]) destination.mkdir(mode=0o700) - os.chown(destination, 1000, 1001) + os.chown(destination, uid, gid) count = collections.Counter() entries = 0 output = destination / 'extended-attributes.jsonl' @@ -40,7 +41,7 @@ def main(): entries += 1 stream.flush() os.fsync(stream.fileno()) - os.chown(output, 1000, 1001) + os.chown(output, uid, gid) summary = {'entries': entries, 'attribute_names': dict(count), 'bytes': output.stat().st_size, 'resource_fork_attributes': count['com.apple.ResourceFork']} (destination / 'README.txt').write_text( @@ -48,7 +49,7 @@ def main(): 'extended-attributes.jsonl 每行记录相对路径与 Base64 编码的原始属性。\n' '包含用户标签、Finder 信息和机器相关安全元数据,请随剪辑备份私下保管,不上传源码仓库。\n' '普通文件已由 rsync 复制;还原至 Mac 时应按需使用这些属性,不要盲目重放机器相关属性。\n') - os.chown(destination / 'README.txt', 1000, 1001) + os.chown(destination / 'README.txt', uid, gid) print(json.dumps(summary, ensure_ascii=False)) diff --git a/tests/test_application.py b/tests/test_application.py index 911b320..d4c0497 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path import socket +import socketserver import tempfile import threading import unittest @@ -91,11 +92,36 @@ class GatewayTests(unittest.TestCase): code, data = self.request('GET', '/app/dayu-diskcopy', 'X-Trim-Userid: 1000\r\nX-Trim-Isadmin: true\r\n') self.assertEqual(code, 200) self.assertIn('大鱼硬盘拷贝'.encode(), data) + self.assertNotIn(b'__DAYU_CSRF__', data) + self.assertIn(self.front.CSRF_TOKEN.encode(), data) - def test_writes_require_request_marker_and_same_origin(self): + def test_writes_require_private_page_nonce_and_no_cross_site_context(self): headers = 'X-Trim-Userid: 1000\r\nX-Trim-Isadmin: true\r\nContent-Length: 0\r\n' self.assertEqual(self.request('POST', '/app/dayu-diskcopy/api/start', headers)[0], 403) - self.assertEqual(self.request('POST', '/app/dayu-diskcopy/api/start', headers + 'X-Dayu-Request: 1\r\nOrigin: https://other.local\r\n')[0], 403) + self.assertEqual(self.request('POST', '/app/dayu-diskcopy/api/start', headers + 'X-Dayu-Request: 1\r\n')[0], 403) + token = 'X-Dayu-Token: ' + self.front.CSRF_TOKEN + '\r\n' + self.assertEqual(self.request('POST', '/app/dayu-diskcopy/api/start', headers + 'X-Dayu-Request: 1\r\n' + token + 'Sec-Fetch-Site: cross-site\r\n')[0], 403) + + def test_valid_nonce_supports_gateway_rewritten_host(self): + class Reply(socketserver.StreamRequestHandler): + def handle(self): + self.rfile.readline() + self.wfile.write(b'{"ok":true,"data":{"accepted":true}}\n') + broker_path = str(Path(self.temp.name) / 'broker.sock') + server = socketserver.UnixStreamServer(broker_path, Reply) + thread = threading.Thread(target=server.handle_request, daemon=True) + thread.start() + headers = ('X-Trim-Userid: 1000\r\nX-Trim-Isadmin: true\r\nContent-Length: 0\r\n' + 'X-Dayu-Request: 1\r\nSec-Fetch-Site: same-origin\r\n' + 'Origin: https://nas.local:5668\r\nX-Dayu-Token: ' + self.front.CSRF_TOKEN + '\r\n') + try: + with patch.object(self.front, 'VAR', Path(self.temp.name)): + code, data = self.request('POST', '/app/dayu-diskcopy/api/mkdir', headers) + self.assertEqual(code, 200) + self.assertIn(b'accepted', data) + finally: + thread.join(timeout=2) + server.server_close() if __name__ == '__main__': diff --git a/verification/2026-11-11-competition-copy.json b/verification/2026-11-11-competition-copy.json new file mode 100644 index 0000000..b6ed1e5 --- /dev/null +++ b/verification/2026-11-11-competition-copy.json @@ -0,0 +1,26 @@ +{ + "date": "2026-11-11", + "directories": [ + "火影秋决", + "LCQ荒野乱斗" + ], + "destination": "/vol5/1000/剪辑盘备份", + "status": "complete", + "logical_source_file_bytes": 548102817612, + "newly_copied_bytes": 501332211263, + "copy_seconds": 2197.872, + "average_copy_MB_per_second": 228.099, + "existing_files_checksum_verified": 64, + "existing_checksum_differences": 0, + "directory_differences": 0, + "new_files_verified_by_rsync_stream_checksums": true, + "independent_full_new_file_readback_performed": false, + "source_writes_unchanged": true, + "source_unmounted": true, + "original_readonly_flag_restored": true, + "destination_syncfs_passed": true, + "destination_user_access_checked": true, + "metadata_archive_entries": 7374, + "metadata_archive_bytes": 1690603, + "source_worker_commit": "604fce4fecc5d4a8ea5f830d653ced830bcc37d7" +} diff --git a/verification/2026-11-11-ntfs-image.json b/verification/2026-11-11-ntfs-image.json new file mode 100644 index 0000000..299fa46 --- /dev/null +++ b/verification/2026-11-11-ntfs-image.json @@ -0,0 +1,7 @@ +{ + "ntfs_image_readonly_mount": true, + "copied_bytes": 1048576, + "source_and_copy_sha256_match": true, + "sha256": "fbbab289f7f94b25736c58be46a994c441fd02552cc6022352e3d86d2fab7c83", + "hardware_ntfs_usb_tested": false +}