Peach: Local-first video metadata scraper and media manager.
feat(auth): 提供可选访问密码与设备会话期限
longmeidao68b4356e5b31
diff --git a/README.en.md b/README.en.mdindex 6519eafa9..ab15453a8 100644--- a/README.en.md+++ b/README.en.md@@ -100,7 +100,7 @@ python3.14 -m venv .venvSetup configures media folders, access scope and ports. Alternatively, use the `peach init` terminal wizard followed by `peach serve`; executables are in the virtual environment directories above.Source deployments default to a sibling `peach-data/` directory. Set `PEACH_DATA_ROOT` for a custom location.-LAN access requires a token: use `peach token` and sign in on each device. Local CA generation requires OpenSSL.+The access password is optional during setup. Leave it blank to allow devices that can reach Peach to enter directly. Configuration lets you set, change or disable the password; the login page offers session durations. Existing deployments retain their current login requirement. Local CA generation requires OpenSSL.See [operations](docs/OPERATIONS.md) for configuration, HTTPS, CloudDrive mounts and non-interactive initialization.## Your datadiff --git a/README.md b/README.mdindex ab99fa053..4a408edec 100644--- a/README.md+++ b/README.md@@ -100,7 +100,7 @@ python3.14 -m venv .venv首次设置页会配置媒体文件夹、访问范围和端口。也可使用 `peach init` 的终端问答,再用 `peach serve` 启动服务;可执行文件位于上述虚拟环境目录。源码部署默认使用仓库同级的 `peach-data/`;自定义位置需设置 `PEACH_DATA_ROOT`。-局域网访问需要口令,由 `peach token` 查看,设备首次访问时登录。本机 CA 生成需要 OpenSSL。+首次设置的访问密码为可选项:留空时,能连接到 Peach 的设备可直接访问。配置页可设置、修改或关闭密码,登录页可选择保持登录时间。已有部署保留当前登录要求。本机 CA 生成需要 OpenSSL。配置、HTTPS、CloudDrive 挂载与非交互初始化详见 [运行与配置](docs/OPERATIONS.md)。## 数据属于自己diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 931f67a08..18cd90bed 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -216,7 +216,9 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt- 托盘管理 HTTP `0.0.0.0:80` 和当前路由选出的 LAN IPv4 上的 HTTPS 443,显式参数、`PEACH_LAN_ADDRESS`、`lan_ipv4()` 依次覆盖;服务日志写入本机 `peach-data/logs`。- 托盘起的服务全是非回环绑定,所以这台机器必须有访问口令,否则 `peach serve` 直接退出、托盘把那条服务显示成未运行。`peach token` 打印 `<数据根>/secrets/auth-token`(没有就现生成),`peach token --rotate` 换一个。换完要重启服务——进程只在启动时读一次——已登录的设备也要重新登录。-- 设备第一次访问跳登录页,把口令贴进去换成一年期的 HttpOnly cookie。reader 取 writer 的复核结果时发的是自己的口令,所以两台机器要用同一份 `auth-token`,复制过去即可。+- 首次设置直接显示「访问密码(可选)」,留空时能连接到 Peach 的设备可直接进入;终端首次初始化默认不设置密码。已有部署没有访问策略文件时保留系统口令登录,已登录的本机浏览器可在配置页设置自己的密码或明确关闭登录要求。+- 密码设置位于本机 `secrets/access.json`,不进数据库或同步目录;密码使用 scrypt 哈希保存。修改或关闭立即生效;修改需要当前密码,关闭还需勾选访问范围确认。保存密码后其他浏览器的会话失效,当前设备保持登录 30 天。+- 登录时可选本次浏览器会话(最长 12 小时)、1 天、7 天、30 天或 1 年;有效期由服务端签名并检查,页面刷新不续期。API 自动化继续使用独立 `X-Token` 凭据,修改访问密码不撤销机器凭据;机器凭据轮换仍走 `peach token --rotate` 并重启服务。- `peach serve` 按平台发布固定 mDNS 主机名,不在源码钉家庭 IP,仍保留 `Zeroconf()` 全合格网卡监听;mDNS 验收必须包含单元测试、运行态 health、DNS-SD、主机名解析和真实 LAN 客户端。- 双机广播分工固定:macOS 是 `peach.local`,Windows 是 `peach-writer.local`,默认值收敛到 `peach.config.MDNS_NAME`,`PEACH_MDNS_NAME` 只做临时覆盖。服务可以同时跑,但两边同时写入会很快冲突转只读。- `.local` 使用本地 CA,不使用 Let's Encrypt。证书与私钥保存在本机 `peach-data/secrets`;TLS 私钥禁用 ACL 继承,只允许实际服务身份、SYSTEM 和 Administrators。macOS/iOS 只安装并信任 `peach-local-ca.crt`,不分发任何私钥。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex ecfd01fcb..ece7b071f 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -7,6 +7,8 @@ JAV 默认封面(官方封面/预览图)与默认大小(大图/小图## 复用决策门槛+- 访问密码复用 Python 3.14 的 [hashlib.scrypt](https://docs.python.org/3.14/library/hashlib.html) 与 OpenSSL,浏览器会话复用 [ItsDangerous 2.2.0](https://itsdangerous.palletsprojects.com/en/stable/)(Pallets 维护、BSD-3-Clause、Python 3.8+、纯 Python、wheel 16 KB、无传递依赖);本机原子配置写入复用 tempfile/os.replace,并将已有 filelock 3.32.4 纳入运行依赖。当前树和 Git 的认证入口已有内部口令、三种拒绝响应和本机配置守卫,继续复用。Starlette SessionMiddleware 采用统一时长并随响应更新会话,不满足每台设备选择固定截止时间的要求;直接使用同源签名库,由 Peach 维护可选密码、截止时间与撤销策略。临时文件 POC 的密码验证、签名验证和篡改拒绝通过,耗时 0.153 秒;真实凭据未读取。新增依赖不包含账户体系或数据库迁移。+- README 交付检查复用系统 Git 的 `diff --no-renames -z` 和 `interpret-trailers --parse`,挂到既有 `agent_worktree.py ready/integrate`;Peach 只定义影响文件与双语声明 policy。本机 Git 2.55.0.windows.3(GPL-2.0,持续维护)与 Python 3.12+ 标准库,无新增依赖或运行时体积。diff --git a/frontend/src/islands/access-settings.tsx b/frontend/src/islands/access-settings.tsxnew file mode 100644index 000000000..0f1f30fd4--- /dev/null+++ b/frontend/src/islands/access-settings.tsx@@ -0,0 +1,77 @@+/** 本机访问密码;表单值只留在提交期间的组件内存中。 */+import { useRef, useState } from 'preact/hooks';+import type { JSX } from 'preact';+import { fieldsetTitle, setActionBusy } from '@peach/legacy/ui';+import { ApiError, apiSend, errorMessage } from '../api';++export interface AccessState { mode: 'open' | 'password' | 'legacy' | 'locked'; revision: string }+type FieldErrors = Partial<Record<'current_password' | 'password' | 'confirmation', string>>;++function PasswordField({ id, label, value, onInput, error, help, current = false }: {+ id: string; label: string; value: string; onInput(value: string): void; error?: string | undefined; help?: string; current?: boolean;+}) {+ return <div class="configfield">+ <label for={id}>{label}</label>+ <input id={id} class="geist-input" type="password" autoComplete={current ? 'current-password' : 'new-password'}+ maxLength={256} value={value} onInput={(event) => onInput(event.currentTarget.value)} required+ aria-invalid={Boolean(error)} aria-describedby={error || help ? `${id}-hint` : undefined} />+ {error || help ? <p id={`${id}-hint`} class={error ? 'configbad' : 'confighelp'} role={error ? 'alert' : undefined}>{error || help}</p> : null}+ </div>;+}++export function AccessSettings({ initial, receipt }: { initial: AccessState; receipt(message: string): void }) {+ const [state, setState] = useState(initial);+ const [current, setCurrent] = useState('');+ const [password, setPassword] = useState('');+ const [confirmation, setConfirmation] = useState('');+ const [disable, setDisable] = useState(false);+ const [error, setError] = useState('');+ const [fields, setFields] = useState<FieldErrors>({});+ const form = useRef<HTMLFormElement>(null);+ const busy = useRef(false);+ const button = useRef<HTMLButtonElement>(null);+ const submit = async (event: JSX.TargetedEvent<HTMLFormElement>) => {+ event.preventDefault();+ if (busy.current) return;+ setError('');+ const issues: FieldErrors = {};+ if (state.mode === 'password' && !current) issues.current_password = '请输入当前访问密码';+ if (!disable) {+ if (password.length < 8 || password.length > 256) issues.password = '访问密码需为 8–256 个字符';+ if (password !== confirmation) issues.confirmation = '两次输入的密码不一致';+ }+ setFields(issues);+ if (Object.keys(issues).length) {+ requestAnimationFrame(() => form.current?.querySelector<HTMLInputElement>('[aria-invalid="true"]')?.focus());+ return;+ }+ busy.current = true; setActionBusy(button.current, true);+ try {+ const next = await apiSend<AccessState>('/api/configuration/access', {+ revision: state.revision, action: disable ? 'disable' : 'set', confirm_disable: disable,+ current_password: current, password: disable ? '' : password, confirmation: disable ? '' : confirmation,+ });+ setState(next); setCurrent(''); setPassword(''); setConfirmation(''); setDisable(false); setFields({});+ receipt(next.mode === 'open' ? '已关闭访问密码' : '已保存访问密码');+ } catch (cause) {+ const payload = cause instanceof ApiError ? cause.body as { errors?: FieldErrors; detail?: { errors?: FieldErrors } } : null;+ const errors = payload?.errors || payload?.detail?.errors;+ if (errors) setFields(errors); else setError(errorMessage(cause));+ }+ finally { busy.current = false; setActionBusy(button.current, false); }+ };+ return <form class="configfieldset" onSubmit={submit} aria-labelledby="accessTitle" noValidate ref={form}>+ <div class="geist-fieldset-content">+ <div dangerouslySetInnerHTML={{ __html: fieldsetTitle('accessTitle', '访问密码') }} />+ <p class="confighelp">{state.mode === 'open' ? '未设置密码,能连接到 Peach 的设备可直接访问。' : state.mode === 'legacy' ? '当前使用系统生成的访问口令。你可以设置自己的密码,或关闭登录要求。' : state.mode === 'locked' ? '访问设置无法读取,请在本机检查配置文件。' : '已设置密码。新设备需要登录,保持登录时间在登录页选择。'}</p>+ {state.mode === 'password' ? <PasswordField id="access-current" label="当前访问密码" value={current} onInput={setCurrent} error={fields.current_password} current /> : null}+ {!disable && state.mode !== 'locked' ? <>+ <PasswordField id="access-password" label={state.mode === 'password' ? '新访问密码' : '设置访问密码'} value={password} onInput={setPassword} error={fields.password} help="至少 8 个字符。保存后其他设备需要重新登录。" />+ <PasswordField id="access-confirm" label="确认访问密码" value={confirmation} onInput={setConfirmation} error={fields.confirmation} />+ </> : null}+ {state.mode === 'password' || state.mode === 'legacy' ? <label class="configcheck"><span class="pcheck"><input type="checkbox" checked={disable} onChange={(event) => setDisable(event.currentTarget.checked)} /><span aria-hidden="true"><svg viewBox="0 0 24 24"><use href="#i-check" /></svg></span></span><span>关闭访问密码,允许能连接到 Peach 的设备直接访问</span></label> : null}+ {error ? <p class="configbad" role="alert">{error}</p> : null}+ </div>+ {state.mode !== 'locked' ? <div class="geist-fieldset-footer"><p>保存后立即生效。</p><button class="geist-button" type="submit" ref={button}>{disable ? '关闭访问密码' : '保存访问密码'}</button></div> : null}+ </form>;+}diff --git a/frontend/src/islands/configuration.tsx b/frontend/src/islands/configuration.tsxindex 47121e0fc..6c225a63e 100644--- a/frontend/src/islands/configuration.tsx+++ b/frontend/src/islands/configuration.tsx@@ -12,6 +12,7 @@ import type { JSX } from 'preact';import { fieldsetTitle, noteHtml, setActionBusy, selectFieldHtml, wireSelectField, MEDIA_SOURCE_ICONS, selectOptionIconHtml } from '@peach/legacy/ui';import { ApiError, apiGet, apiSend, errorMessage } from '../api';+import { AccessSettings, type AccessState } from './access-settings';export interface ConfigurationProps {/** 保存成功后的过去时回执(遗留层的 Toast)。 */@@ -26,6 +27,7 @@ export interface ConfigurationFact {}export interface ConfigurationData {+ access?: AccessState;editable: boolean;/** 不能编辑时给用户看的原因,可编辑时为空。 */notice: string;@@ -336,6 +338,7 @@ export function Configuration({ receipt, data, error }: ConfigurationProps & Sta{data.editable? <ConfigurationForm data={data} receipt={receipt} />: <Html html={noteHtml(data.notice, { variant: 'secondary', label: '只读' })} />}+ {data.access ? <AccessSettings initial={data.access} receipt={receipt} /> : null}<Facts facts={data.facts} /><MountStatus data={data} /></div>diff --git a/frontend/test/access-settings.test.tsx b/frontend/test/access-settings.test.tsxnew file mode 100644index 000000000..5f7fe574f--- /dev/null+++ b/frontend/test/access-settings.test.tsx@@ -0,0 +1,50 @@+import { render } from 'preact';+import { afterEach, expect, it, vi } from 'vitest';+import { AccessSettings } from '../src/islands/access-settings';++const settle = async () => { for (let i = 0; i < 6; i++) await Promise.resolve(); };+afterEach(() => { for (const el of [...document.body.children]) render(null, el); document.body.innerHTML = ''; vi.unstubAllGlobals(); });++it('系统口令可直接转为可选密码且关闭需要明确提交', async () => {+ const host = document.createElement('div'); document.body.append(host);+ const receipt = vi.fn();+ const fetcher = vi.fn(async () => ({ ok: true, json: async () => ({ mode: 'open', revision: 'next' }) }));+ vi.stubGlobal('fetch', fetcher);+ render(<AccessSettings initial={{ mode: 'legacy', revision: 'legacy' }} receipt={receipt} />, host);+ expect(host.querySelector('[autocomplete="current-password"]')).toBeNull();+ const toggle = host.querySelector<HTMLInputElement>('[type="checkbox"]')!;+ toggle.checked = true; toggle.dispatchEvent(new Event('change', { bubbles: true })); await settle();+ expect(host.querySelector('[autocomplete="new-password"]')).toBeNull();+ expect(fetcher).not.toHaveBeenCalled();+ host.querySelector('form')!.dispatchEvent(new Event('submit', { cancelable: true })); await settle();+ expect(JSON.parse((fetcher.mock.calls[0] as unknown as [string, RequestInit])[1].body as string)).toMatchObject({ action: 'disable', confirm_disable: true });+ expect(receipt).toHaveBeenCalledWith('已关闭访问密码');+ expect(host.textContent).toContain('未设置密码');+});++it('已设置的密码需要当前密码且失败原因留在表单中', async () => {+ const host = document.createElement('div'); document.body.append(host);+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 400, json: async () => ({ message: '当前访问密码不正确', errors: { current_password: '当前访问密码不正确' } }) })));+ render(<AccessSettings initial={{ mode: 'password', revision: 'one' }} receipt={vi.fn()} />, host);+ expect(host.querySelector('[autocomplete="current-password"]')).not.toBeNull();+ for (const input of host.querySelectorAll<HTMLInputElement>('input[type="password"]')) {+ input.value = 'example-password'; input.dispatchEvent(new Event('input', { bubbles: true }));+ }+ await settle();+ host.querySelector('form')!.dispatchEvent(new Event('submit', { cancelable: true })); await settle();+ expect(host.querySelector('[role="alert"]')?.textContent).toBe('当前访问密码不正确');+ expect(host.querySelector('[autocomplete="current-password"]')?.getAttribute('aria-invalid')).toBe('true');+});++it('长度提示紧贴字段且提交不合法内容时变为字段错误', async () => {+ const host = document.createElement('div'); document.body.append(host);+ const fetcher = vi.fn(); vi.stubGlobal('fetch', fetcher);+ render(<AccessSettings initial={{ mode: 'open', revision: 'one' }} receipt={vi.fn()} />, host);+ const field = host.querySelector<HTMLInputElement>('#access-password')!;+ expect(field.nextElementSibling?.textContent).toContain('至少 8 个字符');+ host.querySelector('form')!.dispatchEvent(new Event('submit', { cancelable: true })); await settle();+ expect(field.getAttribute('aria-invalid')).toBe('true');+ expect(field.nextElementSibling?.className).toBe('configbad');+ expect(field.nextElementSibling?.getAttribute('role')).toBe('alert');+ expect(fetcher).not.toHaveBeenCalled();+});diff --git a/pyproject.toml b/pyproject.tomlindex 772611f97..d38b02ecb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -27,6 +27,8 @@ classifiers = ["Topic :: Multimedia :: Video",]dependencies = [+ "itsdangerous==2.2.0",+ "filelock==3.32.4","tldextract==5.3.2","APScheduler==3.11.3","beautifulsoup4==4.15.0",diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex c9b6fc07c..480eeede3 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -63,7 +63,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_javdb_cn_names.py","test_link_rediscovery.py", "test_link_label_owner.py","test_agency_entity.py"),- "tooling": ("test_scripts.py", "test_auth.py", "test_cli.py", "test_script_policy.py",+ "tooling": ("test_scripts.py", "test_auth.py", "test_access.py", "test_cli.py", "test_script_policy.py","test_scan.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py","test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py","test_restart_windows_tray.py", "test_deploy_windows_tray.py",diff --git a/src/peach/access.py b/src/peach/access.pynew file mode 100644index 000000000..9372fe683--- /dev/null+++ b/src/peach/access.py@@ -0,0 +1,105 @@+"""本机访问密码与浏览器会话;内部 API 凭据由 auth 管理。"""+from __future__ import annotations++import hashlib+import hmac+import json+import os+from pathlib import Path+import secrets+import tempfile+import time++from itsdangerous import BadData, URLSafeSerializer++DURATIONS = {0: "本次浏览器会话", 1: "1 天", 7: "7 天", 30: "30 天", 365: "1 年"}+COOKIE = "peach_session"+++def load(path: Path | None) -> dict:+ """缺少策略的已有部署继续要求原访问口令,损坏的策略拒绝访问。"""+ if path is None:+ return {"mode": "legacy", "revision": "legacy"}+ try:+ policy = json.loads(path.read_text(encoding="utf-8"))+ if (policy["mode"] not in {"open", "password"}+ or not isinstance(policy["revision"], str)+ or not isinstance(policy["key"], str)):+ raise ValueError("invalid access policy")+ if policy["mode"] == "password" and not all(isinstance(policy[k], str) for k in ("salt", "hash")):+ raise ValueError("invalid password hash")+ return policy+ except FileNotFoundError:+ return {"mode": "legacy", "revision": "legacy"}+ except (OSError, ValueError, KeyError, TypeError):+ return {"mode": "locked", "revision": "locked"}+++def validate_password(password: str, confirmation: str) -> None:+ if password != confirmation:+ raise ValueError("两次输入的密码不一致")+ if password and not 8 <= len(password) <= 256:+ raise ValueError("访问密码需为 8–256 个字符")+++def _digest(password: str, salt: str) -> str:+ return hashlib.scrypt(password.encode("utf-8"), salt=bytes.fromhex(salt),+ n=32768, r=8, p=1, maxmem=67108864, dklen=32).hex()+++def verify(policy: dict, password: str, legacy_token: str = "") -> bool:+ if len(password) > 256:+ return False+ if policy["mode"] == "legacy":+ return bool(legacy_token) and hmac.compare_digest(password.encode(), legacy_token.encode())+ if policy["mode"] != "password":+ return False+ try:+ return hmac.compare_digest(_digest(password, policy["salt"]), policy["hash"])+ except (ValueError, KeyError):+ return False+++def save(path: Path, password: str) -> dict:+ """原子替换策略。每次更改都会撤销已签发的浏览器会话。"""+ validate_password(password, password)+ policy = {"mode": "password" if password else "open",+ "revision": secrets.token_hex(16), "key": secrets.token_urlsafe(32)}+ if password:+ policy["salt"] = secrets.token_hex(16)+ policy["hash"] = _digest(password, policy["salt"])+ path.parent.mkdir(parents=True, exist_ok=True)+ descriptor, temporary = tempfile.mkstemp(dir=path.parent, prefix=".access-", suffix=".json")+ try:+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:+ json.dump(policy, stream)+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ finally:+ Path(temporary).unlink(missing_ok=True)+ return policy+++def public(policy: dict) -> dict:+ return {"mode": policy["mode"], "revision": policy["revision"]}+++def issue(policy: dict, days: int) -> tuple[str, int | None]:+ if days not in DURATIONS:+ raise ValueError("请选择有效的保持登录时间")+ seconds = days * 86400 if days else 43200+ value = URLSafeSerializer(policy["key"], salt="peach-browser-access").dumps(+ {"revision": policy["revision"], "expires": int(time.time()) + seconds})+ return value, seconds if days else None+++def valid_session(policy: dict, value: str) -> bool:+ if policy["mode"] not in {"password", "legacy"} or len(value) > 2048:+ return False+ try:+ payload = URLSafeSerializer(policy["key"], salt="peach-browser-access").loads(value)+ return (payload["revision"] == policy["revision"]+ and isinstance(payload["expires"], int) and payload["expires"] > time.time())+ except (BadData, KeyError, TypeError):+ return Falsediff --git a/src/peach/cli.py b/src/peach/cli.pyindex 4bf88eecd..645749a69 100644--- a/src/peach/cli.py+++ b/src/peach/cli.py@@ -86,6 +86,7 @@ def _serve(args: argparse.Namespace) -> int:settings = PeachSettings(db_path=args.db,token="" if args.setup else _serve_token(args),+ access_path=settings_file.active().directory("secrets") / "access.json",configured=CONFIGURED and not args.setup,docs_enabled=args.docs,mdns_enabled=publish_mdns,@@ -562,11 +563,10 @@ def _print_next_steps(config: settings_file.PeachConfig, *, from_existing: bool)print(f" 1. peach serve --host {config.server.host} --port {config.server.port}")print(" 2. 浏览器打开 http://127.0.0.1:%d/ 确认页面可用。" % config.server.port)if _is_loopback(config.server.host):- print(" 3. 要在局域网访问就改 --host 0.0.0.0:把本机 CA 装进各设备的信任列表,"- "再用 `peach token` 取口令,设备第一次访问时贴进登录页。")+ print(" 3. 要在局域网访问就改 --host 0.0.0.0,并把本机 CA 装进各设备的信任列表。"+ "访问密码为可选项,在配置页设置。")else:- print(" 3. 局域网设备要装本机 CA,并用 `peach token` 取口令,"- "第一次访问时贴进登录页。")+ print(" 3. 局域网设备要装本机 CA。访问密码为可选项,在配置页设置。")def build_parser() -> argparse.ArgumentParser:diff --git a/src/peach/config.py b/src/peach/config.pyindex 2d86c1a5f..4790dfe60 100644--- a/src/peach/config.py+++ b/src/peach/config.py@@ -83,6 +83,7 @@ class PeachSettings:page_path: Path = PROJECT_ROOT / "web" / "index.html"vendor_path: Path = PROJECT_ROOT / "web" / "vendor"token: str = ""+ access_path: Path | None = Nonedocs_enabled: bool = Falsemdns_enabled: bool = Falsemdns_name: str = "peach"diff --git a/src/peach/onboarding.py b/src/peach/onboarding.pyindex ed2fed289..f36407698 100644--- a/src/peach/onboarding.py+++ b/src/peach/onboarding.py@@ -426,6 +426,7 @@ def create_data_tree(config: PeachConfig) -> DataTree:def apply(config: PeachConfig, answers: Answers, *, windows: bool, force: bool = False,+ access_password: str = "",) -> Applied:"""把答案变成一台可以直接起服务的机器:目录、账本、CA、口令、设置文件。@@ -434,6 +435,10 @@ def apply("""prepared = configure(config, answers, windows=windows)tree = create_data_tree(prepared)+ from . import access+ access_path = prepared.directory("secrets") / "access.json"+ if not config.present and not access_path.exists():+ access.save(access_path, access_password)path = settings_file.write(prepared, force=force)return Applied(config=prepared, settings_path=path, tree=tree)diff --git a/src/peach/routes_auth.py b/src/peach/routes_auth.pyindex 807fcf323..0dc4a5980 100644--- a/src/peach/routes_auth.py+++ b/src/peach/routes_auth.py@@ -11,12 +11,40 @@ from __future__ import annotationsimport hmacimport html+from collections import OrderedDict+import threading+import time+from . import access+from starlette.concurrency import run_in_threadpoolfrom urllib.parse import parse_qsfrom fastapi import APIRouter, HTTPException, Requestfrom fastapi.responses import HTMLResponse, RedirectResponse, Responserouter = APIRouter()+_ATTEMPTS: OrderedDict[str, list[float]] = OrderedDict()+_ATTEMPTS_LOCK = threading.Lock()+++def _login_attempt(request: Request) -> None:+ """按连接来源限制密码尝试,保留有界的短期计数。"""+ peer = request.client.host if request.client else "unknown"+ now = time.monotonic()+ with _ATTEMPTS_LOCK:+ attempts = [stamp for stamp in _ATTEMPTS.pop(peer, []) if now - stamp < 60]+ _ATTEMPTS[peer] = attempts+ if len(attempts) >= 10:+ raise HTTPException(429, "尝试次数较多,请一分钟后重试", headers={"Retry-After": "60"})+ attempts.append(now)+ while len(_ATTEMPTS) > 1024:+ _ATTEMPTS.popitem(last=False)+++def _policy(request: Request) -> dict:+ policy = access.load(request.app.state.settings.access_path)+ if policy["mode"] == "legacy":+ policy["key"] = request.app.state.settings.token+ return policydef _first_query_values(request: Request) -> dict[str, str]:@@ -31,8 +59,16 @@ def _first_query_values(request: Request) -> dict[str, str]:def _authorized(request: Request, token: str, args: dict[str, str]) -> bool:if not token:return True- supplied = args.get("t") or request.headers.get("X-Token") or request.cookies.get("tok")- return supplied is not None and hmac.compare_digest(str(supplied), token)+ supplied = args.get("t") or request.headers.get("X-Token")+ if supplied is not None and hmac.compare_digest(str(supplied).encode(), token.encode()):+ return True+ policy = _policy(request)+ if policy["mode"] == "open":+ return True+ if policy["mode"] == "legacy":+ if hmac.compare_digest(request.cookies.get("tok", "").encode(), token.encode()):+ return True+ return access.valid_session(policy, request.cookies.get(access.COOKIE, ""))class PageLoginRequired(Exception):@@ -47,6 +83,9 @@ class AssetLoginRequired(Exception):def require_auth(request: Request) -> dict[str, str]:+ if request.method not in {"GET", "HEAD", "OPTIONS"}:+ from .routes_configuration import same_origin+ same_origin(request)args = _first_query_values(request)if not _authorized(request, request.app.state.settings.token, args):raise HTTPException(status_code=401, detail="unauthorized")@@ -67,18 +106,20 @@ def require_asset_auth(request: Request) -> dict[str, str]:return args-def set_auth_cookie(response: Response, request: Request) -> None:+def set_auth_cookie(response: Response, request: Request, *, days: int = 30, login: bool = False) -> None:token = request.app.state.settings.token- if token:- response.set_cookie(- "tok", token, max_age=31536000, path="/", httponly=True,- samesite="lax", secure=request.url.scheme == "https",- )+ policy = _policy(request)+ response.headers["Cache-Control"] = "no-store"+ if token and policy["mode"] in {"password", "legacy"} and (login or request.query_params.get("t") == token):+ value, max_age = access.issue(policy, days)+ response.set_cookie(access.COOKIE, value, max_age=max_age, path="/", httponly=True,+ samesite="lax", secure=request.url.scheme == "https")+ response.delete_cookie("tok", path="/")def login_html(next_path: str, *, invalid: bool = False) -> str:safe_next = html.escape(next_path, quote=True)- error = '<p role="alert">口令不正确</p>' if invalid else ""+ error = '<p role="alert">访问密码不正确</p>' if invalid else ""return ('<!doctype html><html lang="zh-CN"><meta charset="utf-8">''<meta name="viewport" content="width=device-width,initial-scale=1">'@@ -107,17 +148,25 @@ def login_html(next_path: str, *, invalid: bool = False) -> str:'background:var(--card);box-shadow:var(--shadow)}''.brand{display:flex;align-items:center;gap:12px;margin-bottom:24px}.brand img{width:48px;height:48px}''h1{margin:0;font-size:24px;letter-spacing:.02em}label{display:grid;gap:8px;color:var(--ink-2)}'- 'input{width:100%;height:44px;border:1px solid var(--line);border-radius:11px;'+ 'input,select{width:100%;height:44px;border:1px solid var(--line);border-radius:11px;''background:var(--field);color:var(--ink);padding:0 13px;font:inherit;outline:none}'- 'input:focus{border-color:#ff8b70;box-shadow:0 0 0 3px rgba(255,139,112,.16)}'+ 'input:focus,select:focus{outline:2px solid var(--ink);outline-offset:2px}'+ 'form{display:grid;gap:16px}form p{font-size:13px;color:var(--ink-2);margin:0}'+ '.duration{border:0;padding:0;margin:0;display:grid;grid-template-columns:1fr 1fr;gap:8px}'+ '.duration legend{margin-bottom:8px}.duration label{display:flex;align-items:center;gap:8px}'+ '.duration input{width:16px;height:16px;margin:0;accent-color:var(--ink)}''button{width:100%;height:44px;margin-top:16px;border:0;border-radius:11px;cursor:pointer;'- 'background:linear-gradient(135deg,#ff9a76,#f2557b);color:#130609;font:700 15px system-ui,sans-serif}'- 'button:hover{filter:brightness(1.06)}p[role=alert]{margin:0 0 14px;color:var(--alert)}'+ 'background:var(--ink);color:var(--bg);font:500 15px system-ui,sans-serif}'+ 'button:hover{background:color-mix(in srgb,var(--ink) 88%,var(--bg));color:var(--bg)}p[role=alert]{margin:0 0 14px;color:var(--alert)}''</style><body><main><div class="brand"><img src="/peach-logo.png" alt=""><h1>Peach</h1></div>'f'{error}<form method="post" action="/login">'- '<label>口令 <input name="token" type="password" '+ '<label>访问密码 <input name="token" type="password" maxlength="256" ''autocomplete="current-password" required></label>'f'<input name="next" type="hidden" value="{safe_next}">'+ '<fieldset class="duration"><legend>在此设备保持登录</legend>'+ + ''.join(f'<label><input type="radio" name="days" value="{days}"{" checked" if days == 30 else ""}>{label}</label>'+ for days, label in access.DURATIONS.items())+ + '</fieldset><p>本次浏览器会话最长 12 小时。清除浏览器数据后需要重新登录。</p>''<button type="submit">登录</button></form></main></body></html>')@@ -133,6 +182,9 @@ def login(request: Request, next: str = "/"):@router.post("/login")async def login_submit(request: Request):+ from .routes_configuration import same_origin+ same_origin(request)+ _login_attempt(request)token = request.app.state.settings.tokenform = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True,@@ -141,8 +193,15 @@ async def login_submit(request: Request):next_path = (form.get("next") or ["/"])[0]if not next_path.startswith("/") or next_path.startswith("//"):next_path = "/"- if token and not hmac.compare_digest(str(supplied), token):+ policy = access.load(request.app.state.settings.access_path)+ if token and policy["mode"] != "open" and not await run_in_threadpool(access.verify, policy, supplied, token):return HTMLResponse(login_html(next_path, invalid=True), status_code=401)+ try:+ days = int((form.get("days") or ["30"])[0])+ if days not in access.DURATIONS:+ raise ValueError+ except ValueError:+ raise HTTPException(400, "请选择有效的保持登录时间") from Noneresponse = RedirectResponse(next_path, status_code=303)- set_auth_cookie(response, request)+ set_auth_cookie(response, request, days=days, login=True)return responsediff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.pyindex 9cf28f070..d72b31bed 100644--- a/src/peach/routes_configuration.py+++ b/src/peach/routes_configuration.py@@ -16,8 +16,10 @@ import threadingfrom typing import Anyfrom fastapi import APIRouter, Body, Depends, HTTPException, Request+from fastapi.responses import JSONResponse+from filelock import FileLock, Timeout-from . import distribution, folder_picker, onboarding, settings_file, media_configuration+from . import access, distribution, folder_picker, onboarding, settings_file, media_configurationfrom .routes_auth import require_authfrom .routes_pages import runtime_fact_entries@@ -80,6 +82,7 @@ def snapshot(config) -> dict[str, Any]:editable = managed_configuration()media = config.mounts.get("local") or config.locations.get("local", ())return {+ "access": access.public(access.load(config.directory("secrets") / "access.json")),"editable": editable,"notice": "" if editable else FILE_MANAGED_NOTICE,"revision": revision(config),@@ -134,10 +137,56 @@ def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, Adef same_origin(request: Request) -> None:"""浏览器发来的写请求必须来自 Peach 自己的页面:带了别处的 Origin 就拒。"""origin = request.headers.get("origin")- if origin and origin.rstrip("/") != str(request.base_url).rstrip("/"):+ if request.headers.get("sec-fetch-site") == "cross-site" or (origin and origin.rstrip("/") != str(request.base_url).rstrip("/")):raise HTTPException(403, "请从 Peach 配置页提交")[email protected]("/api/configuration/access")+def save_access(request: Request, body: dict[str, Any] = Body(default_factory=dict),+ _args=Depends(require_auth)):+ local_only(request)+ same_origin(request)+ path = request.app.state.settings.access_path+ if not request.app.state.settings.configured or path is None:+ raise HTTPException(409, "请先完成首次设置")+ if any(not isinstance(body.get(key, ""), str) for key in ("password", "confirmation", "current_password")):+ raise HTTPException(400, "密码需要是文字")+ password = body.get("password", "")+ if body.get("action") not in {"set", "disable"}:+ raise HTTPException(400, "请选择设置或关闭密码")+ if body["action"] == "set" and not password:+ raise HTTPException(400, {"message": "请输入访问密码", "errors": {"password": "请输入访问密码"}})+ if body["action"] == "disable" and body.get("confirm_disable") is not True:+ raise HTTPException(400, "请确认允许能连接到 Peach 的设备直接访问")+ try:+ try:+ access.validate_password(password, body.get("confirmation", ""))+ except ValueError as exc:+ field = "confirmation" if password != body.get("confirmation", "") else "password"+ raise HTTPException(400, {"message": str(exc), "errors": {field: str(exc)}}) from exc+ path.parent.mkdir(parents=True, exist_ok=True)+ with FileLock(str(path.with_suffix(".lock")), timeout=0):+ policy = access.load(path)+ if body.get("revision") != policy["revision"]:+ raise HTTPException(409, "访问设置已变更,请刷新后再保存")+ if policy["mode"] == "locked":+ raise HTTPException(409, "访问设置无法读取,请在本机检查配置文件")+ if policy["mode"] == "password" and not access.verify(policy, body.get("current_password", "")):+ raise HTTPException(400, {"message": "当前访问密码不正确", "errors": {"current_password": "当前访问密码不正确"}})+ policy = access.save(path, password if body["action"] == "set" else "")+ except Timeout:+ raise HTTPException(409, "访问设置正在保存,请稍后重试") from None+ except ValueError as exc:+ raise HTTPException(400, str(exc)) from exc+ response = JSONResponse(access.public(policy), headers={"Cache-Control": "no-store"})+ response.delete_cookie("tok", path="/")+ response.delete_cookie(access.COOKIE, path="/")+ if policy["mode"] == "password":+ from .routes_auth import set_auth_cookie+ set_auth_cookie(response, request, login=True)+ return response++@router.post("/api/pick-folder")def pick_folder(request: Request, body: dict[str, Any] = Body(default_factory=dict),_args=Depends(require_auth)):diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.pyindex 80a9f8791..24e3bf536 100644--- a/src/peach/routes_pages.py+++ b/src/peach/routes_pages.py@@ -507,6 +507,17 @@ def setup_page(opened = " open" if any(errors.get(key) for key in ("data_root", "host", "port", "mdns_name")) else ""fields.append(f'<details{opened}><summary><span>高级设置</span>{_CHEVRON_SVG}</summary>'+ "".join(advanced) + "</details>")+ access_error = str(errors.get("access_password", ""))+ fields.insert(1, '<div class="field"><label for="access-password">访问密码(可选)</label>'+ '<input id="access-password" name="access_password" type="password" maxlength="256" '+ f'aria-invalid="{"true" if access_error else "false"}" '+ 'autocomplete="new-password" aria-describedby="access-help">'+ + (f'<p class="bad" id="access-help" role="alert">{escape(access_error)}</p>' if access_error+ else '<p class="help" id="access-help">留空即可直接访问;设置密码需至少 8 个字符。</p>')+ + '<p class="help">未设置密码时,能连接到 Peach 的设备可直接进入。</p>'+ '<label for="access-confirm">确认访问密码</label><input id="access-confirm" '+ f'aria-invalid="{"true" if access_error else "false"}" '+ 'name="access_confirm" type="password" maxlength="256" autocomplete="new-password"></div>')filled = [path for path in media_dirs if path]if not filled:scan_text = "完成设置后扫描媒体文件夹"@@ -564,8 +575,7 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool, history_gui"<ul>"f"<li>{escape(ledger)}</li>"f"<li>{ca}</li>"- f"<li>访问口令文件:<code>{escape(str(tree.token_path))}</code>;"- "口令内容用 <code>peach token</code> 看,别的设备第一次访问时贴进登录页。</li>"+ "<li>访问密码可在配置页设置、修改或关闭。</li>"f"{scan}""</ul>"f"{mounts}"@@ -698,6 +708,11 @@ async def setup_submit(request: Request):config = settings_file.active()answers, errors = _read_answers(config, submitted, windows=windows)+ from . import access+ try:+ access.validate_password(str(submitted.get("access_password", "")), str(submitted.get("access_confirm", "")))+ except ValueError as exc:+ errors["access_password"] = str(exc)if distribution.standalone() and answers is not None:try:onboarding.check_available_port(answers.port, request.url.port or 80)@@ -715,7 +730,8 @@ async def setup_submit(request: Request):if resolved.path.exists():raise HTTPException(status_code=409, detail="settings file already exists")try:- applied = onboarding.apply(resolved, answers, windows=windows)+ applied = onboarding.apply(resolved, answers, windows=windows,+ access_password=str(submitted.get("access_password", "")))except (OSError, RuntimeError) as exc:return HTMLResponse(setup_page(config, windows=windows, values=submitted,errors={"data_root": str(exc)}, scan_now=scan_now), status_code=400)@@ -723,10 +739,7 @@ async def setup_submit(request: Request):onboarding.request_first_scan(applied.config, "configured" if answers.media_sources is not None else "local")response = HTMLResponse(setup_done_page(applied, windows=windows, scan_requested=scan_now,history_guide=submitted.get("history_guide") == "y"))- if distribution.standalone():- response.set_cookie("tok", auth.read_token(applied.config.directory("secrets")),- httponly=True, samesite="strict", max_age=31536000)- response.headers["Cache-Control"] = "no-store"+ response.headers["Cache-Control"] = "no-store"return responsediff --git a/tests/test_access.py b/tests/test_access.pynew file mode 100644index 000000000..67fc1f884--- /dev/null+++ b/tests/test_access.py@@ -0,0 +1,140 @@+"""可选密码、会话期限与本机管理边界。"""+import tempfile+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import httpx+from fastapi import FastAPI, Depends++from peach import access, routes_auth, routes_configuration+++class AccessTests(unittest.IsolatedAsyncioTestCase):+ async def asyncSetUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.path = Path(self.tmp.name).resolve() / "access.json"+ self.app = FastAPI()+ self.app.state.settings = SimpleNamespace(token="internal-test-token", access_path=self.path, configured=True, mdns_name="peach")+ self.app.include_router(routes_auth.router)+ self.app.include_router(routes_configuration.router)+ @self.app.get("/private")+ def private(_=Depends(routes_auth.require_auth)):+ return {"ok": True}+ @self.app.post("/private")+ def write_private(_=Depends(routes_auth.require_auth)):+ return {"ok": True}+ self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=self.app, client=("127.0.0.1", 1234)), base_url="http://localhost")+ self.addAsyncCleanup(self.client.aclose)+ routes_auth._ATTEMPTS.clear()++ async def login(self, password="correct-password", days=7):+ return await self.client.post("/login", data={"token": password, "days": str(days)})++ async def test_open_access_accepts_first_visit_without_exposing_internal_token(self):+ access.save(self.path, "")+ self.assertEqual((await self.client.get("/private")).status_code, 200)+ page = await self.client.get("/login")+ self.assertEqual(page.status_code, 303)+ self.assertNotIn("internal-test-token", page.text)+ self.assertFalse(self.client.cookies)+ self.assertEqual((await self.client.post("/private", headers={"Origin": "https://evil.example"})).status_code, 403)++ async def test_password_sessions_expire_on_server_and_survive_independent_app_reads(self):+ access.save(self.path, "correct-password")+ self.assertEqual((await self.client.get("/private")).status_code, 401)+ self.assertEqual((await self.login("incorrect")).status_code, 401)+ response = await self.login()+ self.assertEqual(response.status_code, 303)+ self.assertIn("Max-Age=604800", response.headers["set-cookie"])+ self.assertNotIn("internal-test-token", response.headers["set-cookie"])+ self.assertEqual((await self.client.get("/private")).status_code, 200)+ with patch.object(access.time, "time", return_value=access.time.time() + 604801):+ self.assertEqual((await self.client.get("/private")).status_code, 401)++ async def test_browser_session_has_no_persistent_cookie_and_twelve_hour_limit(self):+ policy = access.save(self.path, "correct-password")+ response = await self.login(days=0)+ session_header = next(header for header in response.headers.get_list("set-cookie") if header.startswith(access.COOKIE))+ self.assertNotIn("Max-Age", session_header)+ self.assertIn("HttpOnly", session_header)+ session = self.client.cookies.get(access.COOKIE)+ with patch.object(access.time, "time", return_value=access.time.time() + 43201):+ self.assertFalse(access.valid_session(policy, session))++ async def test_password_change_revokes_sessions_and_disable_is_explicit(self):+ policy = access.save(self.path, "correct-password")+ await self.login()+ old_cookie = self.client.cookies.get(access.COOKIE)+ body = {"revision": policy["revision"], "action": "set", "password": "new-password", "confirmation": "new-password", "current_password": "wrong"}+ self.assertEqual((await self.client.post("/api/configuration/access", json=body)).status_code, 400)+ body["current_password"] = "correct-password"+ response = await self.client.post("/api/configuration/access", json=body)+ self.assertEqual(response.status_code, 200, response.text)+ self.assertFalse(access.valid_session(access.load(self.path), old_cookie))+ self.assertEqual((await self.client.get("/private")).status_code, 200)+ body = {"revision": response.json()["revision"], "action": "disable", "current_password": "new-password"}+ self.assertEqual((await self.client.post("/api/configuration/access", json=body)).status_code, 400)+ body["confirm_disable"] = True+ self.assertEqual((await self.client.post("/api/configuration/access", json=body)).status_code, 200)+ self.client.cookies.clear()+ self.assertEqual((await self.client.get("/private")).status_code, 200)++ async def test_management_rejects_foreign_origin_remote_peer_and_stale_revision(self):+ policy = access.save(self.path, "")+ body = {"revision": policy["revision"], "action": "set", "password": "correct-password", "confirmation": "correct-password"}+ self.assertEqual((await self.client.post("/api/configuration/access", json=body, headers={"Origin": "https://evil.example"})).status_code, 403)+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=self.app, client=("192.168.1.2", 1)), base_url="http://localhost") as remote:+ self.assertEqual((await remote.post("/api/configuration/access", json=body)).status_code, 403)+ body["revision"] = "stale"+ self.assertEqual((await self.client.post("/api/configuration/access", json=body)).status_code, 409)++ async def test_existing_token_cookie_can_configure_without_copying_token_again(self):+ self.assertEqual((await self.client.get("/private")).status_code, 401)+ self.client.cookies.set("tok", "internal-test-token")+ response = await self.client.post("/api/configuration/access", json={"revision": "legacy", "action": "set", "password": "correct-password", "confirmation": "correct-password"})+ self.assertEqual(response.status_code, 200, response.text)+ self.client.cookies.clear()+ self.client.cookies.set("tok", "internal-test-token")+ self.assertEqual((await self.client.get("/private")).status_code, 401)++ async def test_corrupt_policy_fails_closed_and_password_is_not_stored_or_returned(self):+ policy = access.save(self.path, "correct-password")+ self.assertNotIn("correct-password", self.path.read_text())+ self.assertEqual(set(access.public(policy)), {"mode", "revision"})+ self.path.write_text("invalid", encoding="utf-8")+ self.assertEqual((await self.client.get("/private")).status_code, 401)++ async def test_login_duration_tampering_and_repeated_guesses_are_rejected(self):+ access.save(self.path, "correct-password")+ self.assertEqual((await self.login(days=9999)).status_code, 400)+ for _ in range(9):+ await self.login("wrong")+ self.assertEqual((await self.login("wrong")).status_code, 429)++ def test_setup_password_is_visible_optional_and_never_echoed(self):+ from peach import routes_pages, settings_file+ config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.path.parent)})+ html = routes_pages.setup_page(config, windows=True, values={"access_password": "sensitive-password"})+ self.assertIn("访问密码(可选)", html)+ form = html.split('<form method="post" action="/setup">', 1)[1]+ self.assertLess(form.index('name="access_password"'), form.index("高级设置"))+ self.assertNotIn("sensitive-password", html)+ with self.assertRaises(ValueError):+ access.validate_password("correct-password", "different")++ def test_first_setup_initializes_optional_password_but_keeps_existing_policy(self):+ from peach import onboarding, settings_file+ config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.path.parent)})+ path = config.directory("secrets") / "access.json"+ tree = SimpleNamespace(token_created=True)+ with patch.object(onboarding, "configure", return_value=config), patch.object(onboarding, "create_data_tree", return_value=tree), patch.object(settings_file, "write", return_value=config.path):+ onboarding.apply(config, None, windows=True, access_password="correct-password")+ self.assertTrue(access.verify(access.load(path), "correct-password"))+ onboarding.apply(config, None, windows=True)+ self.assertTrue(access.verify(access.load(path), "correct-password"))+ path.unlink()+ onboarding.apply(config, None, windows=True)+ self.assertEqual(access.load(path)["mode"], "open")diff --git a/tests/test_dependency_policy.py b/tests/test_dependency_policy.pyindex 95f05b257..e49df0899 100644--- a/tests/test_dependency_policy.py+++ b/tests/test_dependency_policy.py@@ -42,6 +42,7 @@ class DependencyPolicyTests(unittest.TestCase):"fastapi": "fastapi","filelock": "filelock","httpx": "httpx",+ "itsdangerous": "itsdangerous","numpy": "numpy","objc": "pyobjc-framework-Cocoa","opencc": "opencc",diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 435db782c..b7f092ed8 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -852,7 +852,8 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(legacy.status_code, 303)self.assertEqual(legacy.headers["location"], "/")cookie = legacy.headers["set-cookie"]- self.assertIn("tok=secret", cookie)+ self.assertIn("peach_session=", cookie)+ self.assertNotIn("tok=secret", cookie)self.assertIn("HttpOnly", cookie)response = await self.client.get("/")self.assertEqual(response.status_code, 200)diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 485821b28..92b10e93e 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -2060,7 +2060,7 @@ class FollowWebSourceTests(unittest.TestCase):self.assertPageContains('.fsources[data-layout="compact"] .fsource .fprovider:has(.ficon) .ficon{margin-right:5px}')# 选择要留下来,和 JAV 版式一样存进设置。- self.assertPageContains("javLayout:'big',followLayout:'cozy'")+ self.assertPageContains("followLayout:'cozy'")self.assertPageContains("appSettings.followLayout=value")self.assertPageContains("allowedSetting(appSettings.followLayout,FOLLOW_LAYOUTS.map(([k])=>k),'cozy')")diff --git a/tests/test_onboarding.py b/tests/test_onboarding.pyindex 34101161f..b22a7c196 100644--- a/tests/test_onboarding.py+++ b/tests/test_onboarding.py@@ -547,7 +547,8 @@ class SetupPageTests(_Case):self.assertTrue((self.data_root / "state" / onboarding.SCAN_REQUEST_NAME).is_file())body = response.textself.assertIn("设置完成", body)- self.assertIn("peach token", body)+ self.assertIn("访问密码可在配置页设置、修改或关闭", body)+ self.assertNotIn("peach token", body)self.assertIn("Peach 数据库:", body)self.assertNotIn("账本", body)# 完成页尾部是与配置页共用的运行信息:版本、位置和 FFmpeg 一眼可查。diff --git a/web/css/23-configuration.css b/web/css/23-configuration.cssindex d0c41c42d..4162d85a2 100644--- a/web/css/23-configuration.css+++ b/web/css/23-configuration.css@@ -13,6 +13,8 @@border-top:1px solid var(--line);background:var(--surface)}.configfieldset>.geist-fieldset-footer>p{min-width:0;margin:0 auto 0 0;color:var(--muted);font-size:var(--fs-sm)}.configfield>label,.configfield>.configlabel{display:block;margin:0 0 8px;font-weight:500;color:var(--ink)}+.configpage .geist-input[aria-invalid="true"]{border-color:var(--drop)}+.configpage .geist-input[aria-invalid="true"]:focus{box-shadow:0 0 0 4px color-mix(in srgb,var(--drop) 24%,transparent)}.confighelp{margin:8px 0 0;color:var(--muted);font-size:var(--fs-sm);line-height:1.5}.confighelp a{color:var(--tungsten);text-decoration:none;margin-inline-start:6px}.confighelp a:hover{text-decoration:underline;text-underline-offset:3px}diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.jsindex ae6b75ad6..e5d54a178 100644--- a/web/dist/peach-ui.js+++ b/web/dist/peach-ui.js@@ -284,7 +284,7 @@ async function I(e, t) {if (!n.ok) throw new Se(Ce(r) || `请求失败(${n.status})`, n.status);return r;}-async function we(e, t, n = "POST", r) {+async function L(e, t, n = "POST", r) {let i = await fetch(e, {method: n,...r ? { signal: r } : {},@@ -303,24 +303,24 @@ async function we(e, t, n = "POST", r) {}//#endregion//#region node_modules/preact/hooks/dist/hooks.module.js-var L, R, Te, Ee, De = 0, Oe = [], z = f, ke = z.__b, Ae = z.__r, je = z.diffed, Me = z.__c, Ne = z.unmount, Pe = z.__;-function Fe(e, t) {- z.__h && z.__h(R, e, De || t), De = 0;- var n = R.__H || (R.__H = {+var R, z, we, Te, Ee = 0, De = [], B = f, Oe = B.__b, ke = B.__r, Ae = B.diffed, je = B.__c, Me = B.unmount, Ne = B.__;+function Pe(e, t) {+ B.__h && B.__h(z, e, Ee || t), Ee = 0;+ var n = z.__H || (z.__H = {__: [],__h: []});return e >= n.__.length && n.__.push({}), n.__[e];}-function B(e) {- return De = 1, Ie(Ge, e);+function V(e) {+ return Ee = 1, Fe(We, e);}-function Ie(e, t, n) {- var r = Fe(L++, 2);- if (r.t = e, !r.__c && (r.__ = [n ? n(t) : Ge(void 0, t), function(e) {+function Fe(e, t, n) {+ var r = Pe(R++, 2);+ if (r.t = e, !r.__c && (r.__ = [n ? n(t) : We(void 0, t), function(e) {var t = r.__N ? r.__N[0] : r.__[0], n = r.t(t, e);t !== n && (r.__N = [n, r.__[1]], r.__c.setState({}));- }], r.__c = R, !R.__f)) {+ }], r.__c = z, !z.__f)) {var i = function(e, t, n) {if (!r.__c.__H) return !0;var i = !1, o = r.__c.props !== e;@@ -336,112 +336,112 @@ function Ie(e, t, n) {}return !i || o;};- R.__f = !0;- var a = R.shouldComponentUpdate, o = R.componentWillUpdate;- R.componentWillUpdate = function(e, t, n) {+ z.__f = !0;+ var a = z.shouldComponentUpdate, o = z.componentWillUpdate;+ z.componentWillUpdate = function(e, t, n) {if (this.__e) {var r = a;a = void 0, i(e, t, n), a = r;}o && o.call(this, e, t, n);- }, R.shouldComponentUpdate = i;+ }, z.shouldComponentUpdate = i;}return r.__N || r.__;}-function Le(e, t) {- var n = Fe(L++, 3);- !z.__s && We(n.__H, t) && (n.__ = e, n.u = t, R.__H.__h.push(n));+function Ie(e, t) {+ var n = Pe(R++, 3);+ !B.__s && Ue(n.__H, t) && (n.__ = e, n.u = t, z.__H.__h.push(n));}-function V(e, t) {- var n = Fe(L++, 4);- !z.__s && We(n.__H, t) && (n.__ = e, n.u = t, R.__h.push(n));+function H(e, t) {+ var n = Pe(R++, 4);+ !B.__s && Ue(n.__H, t) && (n.__ = e, n.u = t, z.__h.push(n));}-function H(e) {- return De = 5, Re(function() {+function U(e) {+ return Ee = 5, Le(function() {return { current: e };}, []);}-function Re(e, t) {- var n = Fe(L++, 7);- return We(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;+function Le(e, t) {+ var n = Pe(R++, 7);+ return Ue(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;}-function ze() {- for (var e; e = Oe.shift();) {+function Re() {+ for (var e; e = De.shift();) {var t = e.__H;if (e.__P && t) try {- t.__h.some(He), t.__h.some(Ue), t.__h = [];+ t.__h.some(Ve), t.__h.some(He), t.__h = [];} catch (n) {- t.__h = [], z.__e(n, e.__v);+ t.__h = [], B.__e(n, e.__v);}}}-z.__b = function(e) {- R = null, ke && ke(e);-}, z.__ = function(e, t) {- e && t.__k && t.__k.__m && (e.__m = t.__k.__m), Pe && Pe(e, t);-}, z.__r = function(e) {- Ae && Ae(e), L = 0;- var t = (R = e.__c).__H;- t && (Te === R ? (t.__h = [], R.__h = [], t.__.some(function(e) {+B.__b = function(e) {+ z = null, Oe && Oe(e);+}, B.__ = function(e, t) {+ e && t.__k && t.__k.__m && (e.__m = t.__k.__m), Ne && Ne(e, t);+}, B.__r = function(e) {+ ke && ke(e), R = 0;+ var t = (z = e.__c).__H;+ t && (we === z ? (t.__h = [], z.__h = [], t.__.some(function(e) {e.__N && (e.__ = e.__N), e.u = e.__N = void 0;- })) : (t.__h.some(He), t.__h.some(Ue), t.__h = [], L = 0)), Te = R;-}, z.diffed = function(e) {- je && je(e);+ })) : (t.__h.some(Ve), t.__h.some(He), t.__h = [], R = 0)), we = z;+}, B.diffed = function(e) {+ Ae && Ae(e);var t = e.__c;- t && t.__H && (t.__H.__h.length && (Oe.push(t) !== 1 && Ee === z.requestAnimationFrame || ((Ee = z.requestAnimationFrame) || Ve)(ze)), t.__H.__.some(function(e) {+ t && t.__H && (t.__H.__h.length && (De.push(t) !== 1 && Te === B.requestAnimationFrame || ((Te = B.requestAnimationFrame) || Be)(Re)), t.__H.__.some(function(e) {e.u &&= (e.__H = e.u, void 0);- })), Te = R = null;-}, z.__c = function(e, t) {+ })), we = z = null;+}, B.__c = function(e, t) {t.some(function(e) {try {- e.__h.some(He), e.__h = e.__h.filter(function(e) {- return !e.__ || Ue(e);+ e.__h.some(Ve), e.__h = e.__h.filter(function(e) {+ return !e.__ || He(e);});} catch (n) {t.some(function(e) {e.__h &&= [];- }), t = [], z.__e(n, e.__v);+ }), t = [], B.__e(n, e.__v);}- }), Me && Me(e, t);-}, z.unmount = function(e) {- Ne && Ne(e);+ }), je && je(e, t);+}, B.unmount = function(e) {+ Me && Me(e);var t, n = e.__c;n && n.__H && (n.__H.__.some(function(e) {try {- He(e);+ Ve(e);} catch (e) {t = e;}- }), n.__H = void 0, t && z.__e(t, n.__v));+ }), n.__H = void 0, t && B.__e(t, n.__v));};-var Be = typeof requestAnimationFrame == "function";-function Ve(e) {+var ze = typeof requestAnimationFrame == "function";+function Be(e) {var t, n = function() {- clearTimeout(r), Be && cancelAnimationFrame(t), setTimeout(e);+ clearTimeout(r), ze && cancelAnimationFrame(t), setTimeout(e);}, r = setTimeout(n, 35);- Be && (t = requestAnimationFrame(n));+ ze && (t = requestAnimationFrame(n));}-function He(e) {- var t = R, n = e.__c;- typeof n == "function" && (e.__c = void 0, n()), R = t;+function Ve(e) {+ var t = z, n = e.__c;+ typeof n == "function" && (e.__c = void 0, n()), z = t;}-function Ue(e) {- var t = R;- e.__c = e.__(), R = t;+function He(e) {+ var t = z;+ e.__c = e.__(), z = t;}-function We(e, t) {+function Ue(e, t) {return !e || e.length !== t.length || t.some(function(t, n) {return t !== e[n];});}-function Ge(e, t) {+function We(e, t) {return typeof t == "function" ? t(e) : t;}//#endregion//#region node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js-var Ke = 0;+var Ge = 0;Array.isArray;-function U(e, t, n, r, i, a) {+function W(e, t, n, r, i, a) {t ||= {};var o, s, c = t;if ("ref" in c) for (s in c = {}, t) s == "ref" ? o = t[s] : c[s] = t[s];@@ -456,7 +456,7 @@ function U(e, t, n, r, i, a) {__e: null,__c: null,constructor: void 0,- __v: --Ke,+ __v: --Ge,__i: -1,__u: 0,__source: i,@@ -466,30 +466,158 @@ function U(e, t, n, r, i, a) {return f.vnode && f.vnode(l), l;}//#endregion+//#region src/islands/access-settings.tsx+function Ke({ id: e, label: t, value: n, onInput: r, error: i, help: a, current: o = !1 }) {+ return /* @__PURE__ */ W("div", {+ class: "configfield",+ children: [+ /* @__PURE__ */ W("label", {+ for: e,+ children: t+ }),+ /* @__PURE__ */ W("input", {+ id: e,+ class: "geist-input",+ type: "password",+ autoComplete: o ? "current-password" : "new-password",+ maxLength: 256,+ value: n,+ onInput: (e) => r(e.currentTarget.value),+ required: !0,+ "aria-invalid": !!i,+ "aria-describedby": i || a ? `${e}-hint` : void 0+ }),+ i || a ? /* @__PURE__ */ W("p", {+ id: `${e}-hint`,+ class: i ? "configbad" : "confighelp",+ role: i ? "alert" : void 0,+ children: i || a+ }) : null+ ]+ });+}+function qe({ initial: e, receipt: t }) {+ let [r, i] = V(e), [a, s] = V(""), [c, l] = V(""), [u, d] = V(""), [f, p] = V(!1), [m, h] = V(""), [g, _] = V({}), v = U(null), y = U(!1), b = U(null);+ return /* @__PURE__ */ W("form", {+ class: "configfieldset",+ onSubmit: async (e) => {+ if (e.preventDefault(), y.current) return;+ h("");+ let n = {};+ if (r.mode === "password" && !a && (n.current_password = "请输入当前访问密码"), f || ((c.length < 8 || c.length > 256) && (n.password = "访问密码需为 8–256 个字符"), c !== u && (n.confirmation = "两次输入的密码不一致")), _(n), Object.keys(n).length) {+ requestAnimationFrame(() => v.current?.querySelector("[aria-invalid=\"true\"]")?.focus());+ return;+ }+ y.current = !0, o(b.current, !0);+ try {+ let e = await L("/api/configuration/access", {+ revision: r.revision,+ action: f ? "disable" : "set",+ confirm_disable: f,+ current_password: a,+ password: f ? "" : c,+ confirmation: f ? "" : u+ });+ i(e), s(""), l(""), d(""), p(!1), _({}), t(e.mode === "open" ? "已关闭访问密码" : "已保存访问密码");+ } catch (e) {+ let t = e instanceof Se ? e.body : null, n = t?.errors || t?.detail?.errors;+ n ? _(n) : h(F(e));+ } finally {+ y.current = !1, o(b.current, !1);+ }+ },+ "aria-labelledby": "accessTitle",+ noValidate: !0,+ ref: v,+ children: [/* @__PURE__ */ W("div", {+ class: "geist-fieldset-content",+ children: [+ /* @__PURE__ */ W("div", { dangerouslySetInnerHTML: { __html: n("accessTitle", "访问密码") } }),+ /* @__PURE__ */ W("p", {+ class: "confighelp",+ children: r.mode === "open" ? "未设置密码,能连接到 Peach 的设备可直接访问。" : r.mode === "legacy" ? "当前使用系统生成的访问口令。你可以设置自己的密码,或关闭登录要求。" : r.mode === "locked" ? "访问设置无法读取,请在本机检查配置文件。" : "已设置密码。新设备需要登录,保持登录时间在登录页选择。"+ }),+ r.mode === "password" ? /* @__PURE__ */ W(Ke, {+ id: "access-current",+ label: "当前访问密码",+ value: a,+ onInput: s,+ error: g.current_password,+ current: !0+ }) : null,+ !f && r.mode !== "locked" ? /* @__PURE__ */ W(M, { children: [/* @__PURE__ */ W(Ke, {+ id: "access-password",+ label: r.mode === "password" ? "新访问密码" : "设置访问密码",+ value: c,+ onInput: l,+ error: g.password,+ help: "至少 8 个字符。保存后其他设备需要重新登录。"+ }), /* @__PURE__ */ W(Ke, {+ id: "access-confirm",+ label: "确认访问密码",+ value: u,+ onInput: d,+ error: g.confirmation+ })] }) : null,+ r.mode === "password" || r.mode === "legacy" ? /* @__PURE__ */ W("label", {+ class: "configcheck",+ children: [/* @__PURE__ */ W("span", {+ class: "pcheck",+ children: [/* @__PURE__ */ W("input", {+ type: "checkbox",+ checked: f,+ onChange: (e) => p(e.currentTarget.checked)+ }), /* @__PURE__ */ W("span", {+ "aria-hidden": "true",+ children: /* @__PURE__ */ W("svg", {+ viewBox: "0 0 24 24",+ children: /* @__PURE__ */ W("use", { href: "#i-check" })+ })+ })]+ }), /* @__PURE__ */ W("span", { children: "关闭访问密码,允许能连接到 Peach 的设备直接访问" })]+ }) : null,+ m ? /* @__PURE__ */ W("p", {+ class: "configbad",+ role: "alert",+ children: m+ }) : null+ ]+ }), r.mode === "locked" ? null : /* @__PURE__ */ W("div", {+ class: "geist-fieldset-footer",+ children: [/* @__PURE__ */ W("p", { children: "保存后立即生效。" }), /* @__PURE__ */ W("button", {+ class: "geist-button",+ type: "submit",+ ref: b,+ children: f ? "关闭访问密码" : "保存访问密码"+ })]+ })]+ });+}+//#endregion//#region src/islands/configuration.tsx-var qe = "/api/configuration", Je = "/api/pick-folder", Ye = 8e3, Xe = (e, t) => I(qe, t), W = ({ html: e, class: t }) => /* @__PURE__ */ U("div", {+var Je = "/api/configuration", Ye = "/api/pick-folder", Xe = 8e3, Ze = (e, t) => I(Je, t), G = ({ html: e, class: t }) => /* @__PURE__ */ W("div", {class: t,dangerouslySetInnerHTML: { __html: e }-}), Ze = (e) => !(e instanceof Se) || e.status !== 400 ? null : e.body?.errors ?? null;-function Qe({ facts: e }) {- return /* @__PURE__ */ U("section", {+}), Qe = (e) => !(e instanceof Se) || e.status !== 400 ? null : e.body?.errors ?? null;+function $e({ facts: e }) {+ return /* @__PURE__ */ W("section", {class: "configfieldset","data-geist-fieldset": !0,"aria-labelledby": "configFactsTitle",- children: /* @__PURE__ */ U("div", {+ children: /* @__PURE__ */ W("div", {class: "geist-fieldset-content",- children: [/* @__PURE__ */ U(W, { html: n("configFactsTitle", "运行信息") }), /* @__PURE__ */ U("dl", {+ children: [/* @__PURE__ */ W(G, { html: n("configFactsTitle", "运行信息") }), /* @__PURE__ */ W("dl", {class: "configfacts",- children: e.map((e) => /* @__PURE__ */ U(M, { children: [/* @__PURE__ */ U("dt", { children: e.term }), /* @__PURE__ */ U("dd", { children: [e.value, e.download_url ? /* @__PURE__ */ U("span", {+ children: e.map((e) => /* @__PURE__ */ W(M, { children: [/* @__PURE__ */ W("dt", { children: e.term }), /* @__PURE__ */ W("dd", { children: [e.value, e.download_url ? /* @__PURE__ */ W("span", {class: "confighelp",- children: [" ", /* @__PURE__ */ U("a", {+ children: [" ", /* @__PURE__ */ W("a", {href: e.download_url,target: "_blank",rel: "noreferrer",- children: [e.download_label, /* @__PURE__ */ U("svg", {+ children: [e.download_label, /* @__PURE__ */ W("svg", {"aria-hidden": "true",viewBox: "0 0 24 24",- children: /* @__PURE__ */ U("use", { href: "#i-external-link" })+ children: /* @__PURE__ */ W("use", { href: "#i-external-link" })})]})]}) : null] })] }))@@ -497,15 +625,15 @@ function Qe({ facts: e }) {})});}-function $e({ data: t }) {- let [r, i] = B(t.media_sources), [s, c] = B(""), l = H(null);- Le(() => () => l.current?.abort(), []);+function et({ data: t }) {+ let [r, i] = V(t.media_sources), [s, c] = V(""), l = U(null);+ Ie(() => () => l.current?.abort(), []);let u = async (e) => {if (l.current) return;let t = new AbortController();l.current = t, o(e, !0), c("");try {- let e = await I(qe, t.signal);+ let e = await I(Je, t.signal);t.signal.aborted || i(e.media_sources);} catch (e) {t.signal.aborted || c(F(e));@@ -513,37 +641,37 @@ function $e({ data: t }) {l.current = null, o(e, !1);}};- return r ? /* @__PURE__ */ U("section", {+ return r ? /* @__PURE__ */ W("section", {class: "configfieldset","aria-labelledby": "configMountsTitle",- children: /* @__PURE__ */ U("div", {+ children: /* @__PURE__ */ W("div", {class: "geist-fieldset-content",children: [- /* @__PURE__ */ U(W, { html: n("configMountsTitle", "挂载状态") }),- /* @__PURE__ */ U("dl", {+ /* @__PURE__ */ W(G, { html: n("configMountsTitle", "挂载状态") }),+ /* @__PURE__ */ W("dl", {class: "configfacts",- children: r.map((t) => /* @__PURE__ */ U(M, { children: [/* @__PURE__ */ U("dt", { children: [/* @__PURE__ */ U("span", {+ children: r.map((t) => /* @__PURE__ */ W(M, { children: [/* @__PURE__ */ W("dt", { children: [/* @__PURE__ */ W("span", {"aria-hidden": "true",dangerouslySetInnerHTML: { __html: a(e[t.location]) }}), {local: "本地磁盘",115: "CloudDrive · 115",pikpak: "CloudDrive · PikPak"- }[t.location] || t.location] }), /* @__PURE__ */ U("dd", { children: [+ }[t.location] || t.location] }), /* @__PURE__ */ W("dd", { children: [t.path || "未配置挂载点"," ",- /* @__PURE__ */ U("span", {+ /* @__PURE__ */ W("span", {class: `configstatus ${t.online === !0 ? "online" : t.online === !1 ? "offline" : "unknown"}`,children: t.online === !0 ? "在线" : t.online === !1 ? "离线" : "未检测"})] })] }))}),- s ? /* @__PURE__ */ U("p", {+ s ? /* @__PURE__ */ W("p", {class: "configbad",role: "alert",children: s}) : null,- /* @__PURE__ */ U("button", {+ /* @__PURE__ */ W("button", {type: "button",class: "geist-button",onClick: (e) => u(e.currentTarget),@@ -553,9 +681,9 @@ function $e({ data: t }) {})}) : null;}-function et({ value: t, label: n, onChange: r }) {- let a = H(null), o = H(null), c = H(r);- return c.current = r, V(() => {+function tt({ value: t, label: n, onChange: r }) {+ let a = U(null), o = U(null), c = U(r);+ return c.current = r, H(() => {let r = a.current;r.innerHTML = i([["local", "本地磁盘"],@@ -572,24 +700,24 @@ function et({ value: t, label: n, onChange: r }) {return l.addEventListener("change", u), () => {o.current = null, l.disabled = !0, l.removeEventListener("change", u), r.replaceChildren();};- }, [n]), V(() => {+ }, [n]), H(() => {o.current && (o.current.value = t);- }, [t]), /* @__PURE__ */ U("div", {+ }, [t]), /* @__PURE__ */ W("div", {ref: a,class: "configsourcecontrol"});}-function tt({ data: e, receipt: t }) {+function nt({ data: e, receipt: t }) {let i = e.media_sources?.filter((e) => ["local","115","pikpak"- ].includes(e.location)), [a, s] = B(i?.length ? i.map((e) => e.path) : e.media_dirs.length ? e.media_dirs : [""]), [c, l] = B(i?.map((e) => e.location) ?? []), [u, d] = B(i?.map((e) => e.root) ?? []), [f, p] = B(String(e.port)), [m, h] = B(!1), [g, _] = B([]), [v, y] = B(""), [b, x] = B(""), [S, C] = B(null), [w, T] = B(null), E = H(!1), D = H(e.revision), O = H([]), k = H(null);- V(() => {+ ].includes(e.location)), [a, s] = V(i?.length ? i.map((e) => e.path) : e.media_dirs.length ? e.media_dirs : [""]), [c, l] = V(i?.map((e) => e.location) ?? []), [u, d] = V(i?.map((e) => e.root) ?? []), [f, p] = V(String(e.port)), [m, h] = V(!1), [g, _] = V([]), [v, y] = V(""), [b, x] = V(""), [S, C] = V(null), [w, T] = V(null), E = U(!1), D = U(e.revision), O = U([]), k = U(null);+ H(() => {w !== null && (O.current[w]?.focus(), T(null));- }, [w]), Le(() => {+ }, [w]), Ie(() => {if (!S) return;- let e = setTimeout(() => location.assign(S.url), Ye);+ let e = setTimeout(() => location.assign(S.url), Xe);return () => clearTimeout(e);}, [S]);let A = (e, t) => {@@ -608,7 +736,7 @@ function tt({ data: e, receipt: t }) {if (t.getAttribute("aria-busy") !== "true") {o(t, !0);try {- let { path: t } = await we(Je, { initial: a[e] ?? "" });+ let { path: t } = await L(Ye, { initial: a[e] ?? "" });t && (A(e, t), j(e, ""));} catch (t) {j(e, F(t));@@ -617,24 +745,24 @@ function tt({ data: e, receipt: t }) {}}};- return S ? /* @__PURE__ */ U("div", {+ return S ? /* @__PURE__ */ W("div", {class: "configsaved",role: "status",- children: [/* @__PURE__ */ U(W, { html: r("配置已保存,Peach 正在重新启动。", {+ children: [/* @__PURE__ */ W(G, { html: r("配置已保存,Peach 正在重新启动。", {variant: "success",label: "已保存"- }) }), /* @__PURE__ */ U("p", {+ }) }), /* @__PURE__ */ W("p", {class: "confighelp",children: ["几秒后自动打开新地址;没跳转就点 ",- /* @__PURE__ */ U("a", {+ /* @__PURE__ */ W("a", {href: S.url,children: "进入馆藏"}),"。"]})]- }) : /* @__PURE__ */ U("form", {+ }) : /* @__PURE__ */ W("form", {class: "configfieldset","data-geist-fieldset": !0,"aria-labelledby": "configTitle",@@ -642,7 +770,7 @@ function tt({ data: e, receipt: t }) {if (n.preventDefault(), !E.current) {E.current = !0, o(k.current, !0), x("");try {- let n = await we(qe, {+ let n = await L(Je, {revision: D.current,media_dirs: a,...e.media_sources ? { media_sources: a.map((e, t) => ({@@ -655,7 +783,7 @@ function tt({ data: e, receipt: t }) {});D.current = n.revision, _([]), y(""), t("已保存配置"), C(n);} catch (e) {- let t = Ze(e);+ let t = Qe(e);t ? (_(t.media_dirs ?? []), y(t.port ?? "")) : (_([]), y(""), x(F(e)));} finally {E.current = !1, o(k.current, !1);@@ -663,30 +791,30 @@ function tt({ data: e, receipt: t }) {}},noValidate: !0,- children: [/* @__PURE__ */ U("div", {+ children: [/* @__PURE__ */ W("div", {class: "geist-fieldset-content",children: [- /* @__PURE__ */ U(W, { html: n("configTitle", "这台电脑") }),- /* @__PURE__ */ U("div", {+ /* @__PURE__ */ W(G, { html: n("configTitle", "这台电脑") }),+ /* @__PURE__ */ W("div", {class: "configfield",children: [- /* @__PURE__ */ U("span", {+ /* @__PURE__ */ W("span", {class: "configlabel",id: "configDirsLabel",children: "媒体文件夹"}),- /* @__PURE__ */ U("div", {+ /* @__PURE__ */ W("div", {class: "configdirs",role: "group","aria-labelledby": "configDirsLabel",- children: a.map((t, n) => /* @__PURE__ */ U("div", {+ children: a.map((t, n) => /* @__PURE__ */ W("div", {class: "configdir",children: [- /* @__PURE__ */ U("span", {+ /* @__PURE__ */ W("span", {class: "configpathlabel",children: ["本机文件夹 ", n + 1]}),- /* @__PURE__ */ U("input", {+ /* @__PURE__ */ W("input", {class: "geist-input",type: "text",value: t,@@ -697,33 +825,33 @@ function tt({ data: e, receipt: t }) {O.current[n] = e;}}),- /* @__PURE__ */ U("button", {+ /* @__PURE__ */ W("button", {type: "button",class: "geist-button configpick","aria-label": "选择文件夹",onClick: (e) => M(n, e.currentTarget),- children: /* @__PURE__ */ U("svg", {+ children: /* @__PURE__ */ W("svg", {viewBox: "0 0 24 24","aria-hidden": "true",- children: /* @__PURE__ */ U("use", { href: "#i-folder-search" })+ children: /* @__PURE__ */ W("use", { href: "#i-folder-search" })})}),- a.length > 1 ? /* @__PURE__ */ U("button", {+ a.length > 1 ? /* @__PURE__ */ W("button", {type: "button",class: "geist-button configrm","aria-label": "移除这个文件夹",onClick: () => te(n),- children: /* @__PURE__ */ U("svg", {+ children: /* @__PURE__ */ W("svg", {viewBox: "0 0 24 24","aria-hidden": "true",- children: /* @__PURE__ */ U("use", { href: "#i-x" })+ children: /* @__PURE__ */ W("use", { href: "#i-x" })})}) : null,- /* @__PURE__ */ U("div", {+ /* @__PURE__ */ W("div", {class: "configsource",- children: [/* @__PURE__ */ U("div", {+ children: [/* @__PURE__ */ W("div", {class: "configsourcelabel",- children: ["媒体来源", /* @__PURE__ */ U(et, {+ children: ["媒体来源", /* @__PURE__ */ W(tt, {label: `媒体来源 ${n + 1}`,value: c[n] || "local",onChange: (e) => {@@ -731,7 +859,7 @@ function tt({ data: e, receipt: t }) {t[n] = e, l(t);}})]- }), e.windows === !1 ? /* @__PURE__ */ U("label", { children: ["Windows 中的对应路径", /* @__PURE__ */ U("input", {+ }), e.windows === !1 ? /* @__PURE__ */ W("label", { children: ["Windows 中的对应路径", /* @__PURE__ */ W("input", {class: "geist-input","aria-label": `Windows 中的对应路径 ${n + 1}`,value: u[n] || "",@@ -742,7 +870,7 @@ function tt({ data: e, receipt: t }) {}})] }) : null]}),- g[n] ? /* @__PURE__ */ U("p", {+ g[n] ? /* @__PURE__ */ W("p", {class: "configbad",role: "alert",children: g[n]@@ -750,61 +878,61 @@ function tt({ data: e, receipt: t }) {]}, n))}),- /* @__PURE__ */ U("button", {+ /* @__PURE__ */ W("button", {type: "button",class: "geist-button configadd",onClick: ee,children: "添加文件夹"}),- c.some((e) => e === "115" || e === "pikpak") ? /* @__PURE__ */ U("p", {+ c.some((e) => e === "115" || e === "pikpak") ? /* @__PURE__ */ W("p", {class: "confighelp",- children: ["先在 CloudDrive 登录网盘并完成挂载。", /* @__PURE__ */ U("a", {+ children: ["先在 CloudDrive 登录网盘并完成挂载。", /* @__PURE__ */ W("a", {href: "https://www.clouddrive2.com/help.html",target: "_blank",rel: "noreferrer",- children: ["挂载帮助", /* @__PURE__ */ U("svg", {+ children: ["挂载帮助", /* @__PURE__ */ W("svg", {"aria-hidden": "true",viewBox: "0 0 24 24",- children: /* @__PURE__ */ U("use", { href: "#i-external-link" })+ children: /* @__PURE__ */ W("use", { href: "#i-external-link" })})]})]}) : null,- c.some((e) => e === "115" || e === "pikpak") ? e.mount_dependencies?.filter((e) => !e.available).map((e) => /* @__PURE__ */ U("p", {+ c.some((e) => e === "115" || e === "pikpak") ? e.mount_dependencies?.filter((e) => !e.available).map((e) => /* @__PURE__ */ W("p", {class: "confighelp",children: ["未检测到 ",e.name,"。",- /* @__PURE__ */ U("a", {+ /* @__PURE__ */ W("a", {href: e.download_url,target: "_blank",rel: "noreferrer",children: ["下载 ",e.name,- /* @__PURE__ */ U("svg", {+ /* @__PURE__ */ W("svg", {"aria-hidden": "true",viewBox: "0 0 24 24",- children: /* @__PURE__ */ U("use", { href: "#i-external-link" })+ children: /* @__PURE__ */ W("use", { href: "#i-external-link" })})]})]})) : null,- e.windows === !1 ? /* @__PURE__ */ U("p", {+ e.windows === !1 ? /* @__PURE__ */ W("p", {class: "confighelp",children: "本机文件夹是这台电脑读取媒体的位置。Windows 中的对应路径用于匹配馆藏中已有的路径,例如 B:\\ 对应本机挂载文件夹。"}) : null]}),- e.port_editable === !1 ? null : /* @__PURE__ */ U("div", {+ e.port_editable === !1 ? null : /* @__PURE__ */ W("div", {class: "configfield",children: [- /* @__PURE__ */ U("label", {+ /* @__PURE__ */ W("label", {for: "configPort",children: "本机访问端口"}),- /* @__PURE__ */ U("input", {+ /* @__PURE__ */ W("input", {id: "configPort",class: "geist-input",type: "text",@@ -813,43 +941,43 @@ function tt({ data: e, receipt: t }) {"aria-invalid": v ? "true" : void 0,onInput: (e) => p(e.currentTarget.value)}),- v ? /* @__PURE__ */ U("p", {+ v ? /* @__PURE__ */ W("p", {class: "configbad",role: "alert",children: v}) : null,- /* @__PURE__ */ U("p", {+ /* @__PURE__ */ W("p", {class: "confighelp",children: "浏览器地址里冒号后面的数字,一般不用改。"})]}),- /* @__PURE__ */ U("label", {+ /* @__PURE__ */ W("label", {class: "configcheck",- children: [/* @__PURE__ */ U("span", {+ children: [/* @__PURE__ */ W("span", {class: "pcheck",- children: [/* @__PURE__ */ U("input", {+ children: [/* @__PURE__ */ W("input", {type: "checkbox",checked: m,onChange: (e) => h(e.currentTarget.checked)- }), /* @__PURE__ */ U("span", {+ }), /* @__PURE__ */ W("span", {"aria-hidden": "true",- children: /* @__PURE__ */ U("svg", {+ children: /* @__PURE__ */ W("svg", {viewBox: "0 0 24 24",- children: /* @__PURE__ */ U("use", { href: "#i-check" })+ children: /* @__PURE__ */ W("use", { href: "#i-check" })})})]- }), /* @__PURE__ */ U("span", { children: "保存后扫描媒体文件夹" })]+ }), /* @__PURE__ */ W("span", { children: "保存后扫描媒体文件夹" })]}),- b ? /* @__PURE__ */ U(W, { html: r(b, {+ b ? /* @__PURE__ */ W(G, { html: r(b, {variant: "error",label: "没有保存"}) }) : null]- }), /* @__PURE__ */ U("div", {+ }), /* @__PURE__ */ W("div", {class: "geist-fieldset-footer","data-geist-fieldset-footer": !0,- children: [/* @__PURE__ */ U("p", { children: e.port_editable === !1 ? "保存后 Peach 会重新载入配置。" : "保存后 Peach 会重新启动,端口改了就用新地址打开。" }), /* @__PURE__ */ U("button", {+ children: [/* @__PURE__ */ W("p", { children: e.port_editable === !1 ? "保存后 Peach 会重新载入配置。" : "保存后 Peach 会重新启动,端口改了就用新地址打开。" }), /* @__PURE__ */ W("button", {type: "submit",class: "geist-button primary",ref: k,@@ -858,47 +986,51 @@ function tt({ data: e, receipt: t }) {})]});}-function nt({ receipt: e, data: t, error: n }) {- return n || !t ? /* @__PURE__ */ U(W, {+function rt({ receipt: e, data: t, error: n }) {+ return n || !t ? /* @__PURE__ */ W(G, {class: "configpage",html: r(n || "没有读到配置", {variant: "error",label: "打不开配置"})- }) : /* @__PURE__ */ U("div", {+ }) : /* @__PURE__ */ W("div", {class: "configpage",children: [- t.editable ? /* @__PURE__ */ U(tt, {+ t.editable ? /* @__PURE__ */ W(nt, {data: t,receipt: e- }) : /* @__PURE__ */ U(W, { html: r(t.notice, {+ }) : /* @__PURE__ */ W(G, { html: r(t.notice, {variant: "secondary",label: "只读"}) }),- /* @__PURE__ */ U(Qe, { facts: t.facts }),- /* @__PURE__ */ U($e, { data: t })+ t.access ? /* @__PURE__ */ W(qe, {+ initial: t.access,+ receipt: e+ }) : null,+ /* @__PURE__ */ W($e, { facts: t.facts }),+ /* @__PURE__ */ W(et, { data: t })]});}//#endregion//#region node_modules/@preact/signals-core/dist/signals-core.module.js-var rt = Symbol.for("preact-signals");-function it() {- if (J > 1) J--;+var it = Symbol.for("preact-signals");+function at() {+ if (q > 1) q--;else {var e, t = !1;for ((function() {- var e = ut;- for (ut = void 0; e !== void 0;) {+ var e = pt;+ for (pt = void 0; e !== void 0;) {var t = e.S;if (t.v === e.v) for (var n = t.t; n !== void 0; n = n.x) n.i === e.i && (n.i = t.i);e = e.o;}- })(); q !== void 0;) {- var n = q;- for (q = void 0, st++; n !== void 0;) {+ })(); lt !== void 0;) {+ var n = lt;+ for (lt = void 0, ut++; n !== void 0;) {var r = n.u;- if (n.u = void 0, n.f &= -3, !(8 & n.f) && mt(n)) try {+ if (n.u = void 0, n.f &= -3, !(8 & n.f) && _t(n)) try {n.c();} catch (n) {t ||= (e = n, !0);@@ -906,30 +1038,30 @@ function it() {n = r;}}- if (st = 0, J--, t) throw e;+ if (ut = 0, q--, t) throw e;}}-function at(e) {- if (J > 0) return e();- lt = ++ct, J++;+function ot(e) {+ if (q > 0) return e();+ ft = ++dt, q++;try {return e();} finally {- it();+ at();}}-var G, K = void 0;-function ot(e) {- var t = K, n = G;- K = void 0, G = void 0;+var st, K = void 0;+function ct(e) {+ var t = K, n = st;+ K = void 0, st = void 0;try {return e();} finally {- K = t, G = n;+ K = t, st = n;}}-var q = void 0, J = 0, st = 0, ct = 0, lt = 0, ut = void 0, dt = 0;-function ft(e) {+var lt = void 0, q = 0, ut = 0, dt = 0, ft = 0, pt = void 0, mt = 0;+function ht(e) {if (K !== void 0) {var t = e.n;if (t === void 0 || t.t !== K) return t = {@@ -945,77 +1077,77 @@ function ft(e) {if (t.i === -1) return t.i = 0, t.n !== void 0 && (t.n.p = t.p, t.p !== void 0 && (t.p.n = t.n), t.p = K.s, t.n = void 0, K.s.n = t, K.s = t), t;}}-function Y(e, t) {+function J(e, t) {this.v = e, this.i = 0, this.n = void 0, this.t = void 0, this.l = 0, this.W = t?.watched, this.Z = t?.unwatched, this.name = t?.name;}-Y.prototype.brand = rt, Y.prototype.h = function() {+J.prototype.brand = it, J.prototype.h = function() {return !0;-}, Y.prototype.S = function(e) {+}, J.prototype.S = function(e) {var t = this, n = this.t;- n !== e && e.e === void 0 && (e.x = n, this.t = e, n === void 0 ? ot(function() {+ n !== e && e.e === void 0 && (e.x = n, this.t = e, n === void 0 ? ct(function() {var e;(e = t.W) == null || e.call(t);}) : n.e = e);-}, Y.prototype.U = function(e) {+}, J.prototype.U = function(e) {var t = this;if (this.t !== void 0) {var n = e.e, r = e.x;- n !== void 0 && (n.x = r, e.e = void 0), r !== void 0 && (r.e = n, e.x = void 0), e === this.t && (this.t = r, r === void 0 && ot(function() {+ n !== void 0 && (n.x = r, e.e = void 0), r !== void 0 && (r.e = n, e.x = void 0), e === this.t && (this.t = r, r === void 0 && ct(function() {var e;(e = t.Z) == null || e.call(t);}));}-}, Y.prototype.subscribe = function(e) {+}, J.prototype.subscribe = function(e) {var t = this;- return xt(function() {+ return Z(function() {var n = t.value;- ot(function() {+ ct(function() {return e(n);});}, { name: "sub" });-}, Y.prototype.valueOf = function() {+}, J.prototype.valueOf = function() {return this.value;-}, Y.prototype.toString = function() {+}, J.prototype.toString = function() {return this.value + "";-}, Y.prototype.toJSON = function() {+}, J.prototype.toJSON = function() {return this.value;-}, Y.prototype.peek = function() {+}, J.prototype.peek = function() {var e = this;- return ot(function() {+ return ct(function() {return e.value;});-}, Object.defineProperty(Y.prototype, "value", {+}, Object.defineProperty(J.prototype, "value", {get: function() {- var e = ft(this);+ var e = ht(this);return e !== void 0 && (e.i = this.i), this.v;},set: function(e) {if (e !== this.v) {- if (st > 100) throw Error("Cycle detected");+ if (ut > 100) throw Error("Cycle detected");(function(e) {- J !== 0 && st === 0 && e.l !== lt && (e.l = lt, ut = {+ q !== 0 && ut === 0 && e.l !== ft && (e.l = ft, pt = {S: e,v: e.v,i: e.i,- o: ut+ o: pt});- })(this), this.v = e, this.i++, dt++, J++;+ })(this), this.v = e, this.i++, mt++, q++;try {for (var t = this.t; t !== void 0; t = t.x) t.t.N();} finally {- it();+ at();}}}});-function pt(e, t) {- return new Y(e, t);+function gt(e, t) {+ return new J(e, t);}-function mt(e) {+function _t(e) {for (var t = e.s; t !== void 0; t = t.n) if (t.S.i !== t.i || !t.S.h() || t.S.i !== t.i) return !0;return !1;}-function ht(e) {+function vt(e) {for (var t = e.s; t !== void 0; t = t.n) {var n = t.S.n;if (n !== void 0 && (t.r = n), t.S.n = t, t.i = -1, t.n === void 0) {@@ -1024,81 +1156,81 @@ function ht(e) {}}}-function gt(e) {+function yt(e) {for (var t = e.s, n = void 0; t !== void 0;) {var r = t.p;t.i === -1 ? (t.S.U(t), r !== void 0 && (r.n = t.n), t.n !== void 0 && (t.n.p = r)) : n = t, t.S.n = t.r, t.r !== void 0 && (t.r = void 0), t = r;}e.s = n;}-function X(e, t) {- Y.call(this, void 0, t), this.x = e, this.s = void 0, this.g = dt - 1, this.f = 4;+function Y(e, t) {+ J.call(this, void 0, t), this.x = e, this.s = void 0, this.g = mt - 1, this.f = 4;}-X.prototype = new Y(), X.prototype.h = function() {+Y.prototype = new J(), Y.prototype.h = function() {if (this.f &= -3, 1 & this.f) return !1;- if ((36 & this.f) == 32 || (this.f &= -5, this.g === dt)) return !0;- if (this.g = dt, this.f |= 1, this.i > 0 && !mt(this)) return this.f &= -2, !0;+ if ((36 & this.f) == 32 || (this.f &= -5, this.g === mt)) return !0;+ if (this.g = mt, this.f |= 1, this.i > 0 && !_t(this)) return this.f &= -2, !0;var e = K;try {- ht(this), K = this;+ vt(this), K = this;var t = this.x();(16 & this.f || this.v !== t || this.i === 0) && (this.v = t, this.f &= -17, this.i++);} catch (e) {this.v = e, this.f |= 16, this.i++;}- return K = e, gt(this), this.f &= -2, !0;-}, X.prototype.S = function(e) {+ return K = e, yt(this), this.f &= -2, !0;+}, Y.prototype.S = function(e) {if (this.t === void 0) {this.f |= 36;for (var t = this.s; t !== void 0; t = t.n) t.S.S(t);}- Y.prototype.S.call(this, e);-}, X.prototype.U = function(e) {- if (this.t !== void 0 && (Y.prototype.U.call(this, e), this.t === void 0)) {+ J.prototype.S.call(this, e);+}, Y.prototype.U = function(e) {+ if (this.t !== void 0 && (J.prototype.U.call(this, e), this.t === void 0)) {this.f &= -33;for (var t = this.s; t !== void 0; t = t.n) t.S.U(t);}-}, X.prototype.N = function() {+}, Y.prototype.N = function() {if (!(2 & this.f)) {this.f |= 6;for (var e = this.t; e !== void 0; e = e.x) e.t.N();}-}, Object.defineProperty(X.prototype, "value", { get: function() {+}, Object.defineProperty(Y.prototype, "value", { get: function() {if (1 & this.f) throw Error("Cycle detected");- var e = ft(this);+ var e = ht(this);if (this.h(), e !== void 0 && (e.i = this.i), 16 & this.f) throw this.v;return this.v;} });-function _t(e, t) {- return new X(e, t);+function bt(e, t) {+ return new Y(e, t);}-function vt(e) {+function xt(e) {var t = e.m;if (e.m = void 0, typeof t == "function") {- J++;+ q++;var n = K;K = void 0;try {t();} catch (t) {- throw e.f &= -2, e.f |= 8, yt(e), t;+ throw e.f &= -2, e.f |= 8, St(e), t;} finally {- K = n, it();+ K = n, at();}}}-function yt(e) {+function St(e) {for (var t = e.s; t !== void 0; t = t.n) t.S.U(t);- e.x = void 0, e.s = void 0, vt(e);+ e.x = void 0, e.s = void 0, xt(e);}-function bt(e) {+function Ct(e) {if (K !== this) throw Error("Out-of-order effect");- gt(this), K = e, this.f &= -2, 8 & this.f && yt(this), it();+ yt(this), K = e, this.f &= -2, 8 & this.f && St(this), at();}-function Z(e, t) {- this.x = e, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t?.name, G && G.push(this);+function X(e, t) {+ this.x = e, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t?.name, st && st.push(this);}-Z.prototype.c = function() {+X.prototype.c = function() {var e = this.S();try {if (8 & this.f || this.x === void 0) return;@@ -1107,20 +1239,20 @@ Z.prototype.c = function() {} finally {e();}-}, Z.prototype.S = function() {+}, X.prototype.S = function() {if (1 & this.f) throw Error("Cycle detected");- this.f |= 1, this.f &= -9, vt(this), ht(this), J++;+ this.f |= 1, this.f &= -9, xt(this), vt(this), q++;var e = K;- return K = this, bt.bind(this, e);-}, Z.prototype.N = function() {- 2 & this.f || (this.f |= 2, this.u = q, q = this);-}, Z.prototype.d = function() {- this.f |= 8, 1 & this.f || yt(this);-}, Z.prototype.dispose = function() {+ return K = this, Ct.bind(this, e);+}, X.prototype.N = function() {+ 2 & this.f || (this.f |= 2, this.u = lt, lt = this);+}, X.prototype.d = function() {+ this.f |= 8, 1 & this.f || St(this);+}, X.prototype.dispose = function() {this.d();};-function xt(e, t) {- var n = new Z(e, t);+function Z(e, t) {+ var n = new X(e, t);try {n.c();} catch (e) {@@ -1131,35 +1263,35 @@ function xt(e, t) {}//#endregion//#region node_modules/@preact/signals/dist/signals.module.js-var St, Ct, wt = typeof window < "u" && !!window.__PREACT_SIGNALS_DEVTOOLS__, Tt = [];-xt(function() {- St = this.N;+var wt, Tt, Et = typeof window < "u" && !!window.__PREACT_SIGNALS_DEVTOOLS__, Dt = [];+Z(function() {+ wt = this.N;})();function Q(e, t) {f[e] = t.bind(null, f[e] || function() {});}-function Et(e) {- if (Ct) {- var t = Ct;- Ct = void 0, t();+function Ot(e) {+ if (Tt) {+ var t = Tt;+ Tt = void 0, t();}- Ct = e && e.S();+ Tt = e && e.S();}-function Dt(e) {- var t = this, n = e.data, r = kt(n);+function kt(e) {+ var t = this, n = e.data, r = jt(n);r.name = "ReactiveDom", r.value = n;- var i = Re(function() {+ var i = Le(function() {for (var e = t, n = t.__v; n = n.__;) if (n.__c) {n.__c.__$f |= 4;break;}- var i = _t(function() {+ var i = bt(function() {var e = r.value.value;return e === 0 ? 0 : !0 === e ? "" : e || "";- }), a = _t(function() {+ }), a = bt(function() {return !Array.isArray(i.value) && !m(i.value);- }), o = xt(function() {- if (this.N = Mt, a.value) {+ }), o = Z(function() {+ if (this.N = Pt, a.value) {var t = i.value;e.__v && e.__v.__e && e.__v.__e.nodeType === 3 && (e.__v.__e.data = t);}@@ -1170,14 +1302,14 @@ function Dt(e) {}, []), a = i[0], o = i[1];return a.value ? o.peek() : o.value;}-Dt.displayName = "ReactiveTextNode", Object.defineProperties(Y.prototype, {+kt.displayName = "ReactiveTextNode", Object.defineProperties(J.prototype, {constructor: {configurable: !0,value: void 0},type: {configurable: !0,- value: Dt+ value: kt},props: {configurable: !0,@@ -1197,30 +1329,30 @@ Dt.displayName = "ReactiveTextNode", Object.defineProperties(Y.prototype, {var n, r = t.props;for (var i in r) if (i !== "children") {var a = r[i];- a instanceof Y && (n || (t.__np = n = {}), n[i] = a, r[i] = a.peek());+ a instanceof J && (n || (t.__np = n = {}), n[i] = a, r[i] = a.peek());}}e(t);}), Q("__r", function(e, t) {if (e(t), t.type !== M) {- Et();+ Ot();var n, r = t.__c;r && (r.__$f &= -2, (n = r.__$u) === void 0 && (r.__$u = n = function(e, t) {var n;- return xt(function() {+ return Z(function() {n = this;}, { name: t }), n.c = e, n;}(function(e) {return function() {var t;- wt && ((t = this.y) == null || t.call(this)), e.__$f |= 1, e.setState({});+ Et && ((t = this.y) == null || t.call(this)), e.__$f |= 1, e.setState({});};- }(r), typeof t.type == "function" ? t.type.displayName || t.type.name : ""))), Et(n);+ }(r), typeof t.type == "function" ? t.type.displayName || t.type.name : ""))), Ot(n);}}), Q("__e", function(e, t, n, r) {- Et(), e(t, n, r);+ Ot(), e(t, n, r);}), Q("diffed", function(e, t) {- Et();+ Ot();var n;if (typeof t.type == "string" && (n = t.__e)) {var r = t.__np, i = t.props, a = n.U;@@ -1230,19 +1362,19 @@ Dt.displayName = "ReactiveTextNode", Object.defineProperties(Y.prototype, {}if (r) for (var c in a || (a = {}, n.U = a), r) {var l = a[c], u = r[c];- l === void 0 ? (l = Ot(n, c, u, i), a[c] = l) : l.o(u, i);+ l === void 0 ? (l = At(n, c, u, i), a[c] = l) : l.o(u, i);}}e(t);});-function Ot(e, t, n, r) {- var i = t in e && e.ownerSVGElement === void 0, a = pt(n);+function At(e, t, n, r) {+ var i = t in e && e.ownerSVGElement === void 0, a = gt(n);return {o: function(e, t) {a.value = e, r = t;},- d: xt(function() {- this.N = Mt;+ d: Z(function() {+ this.N = Pt;var n = a.value.value;r[t] !== n && (r[t] = n, i ? e[t] = n : n != null && (!1 !== n || t[4] === "-") ? e.setAttribute(t, n) : e.removeAttribute(t));})@@ -1286,44 +1418,44 @@ Q("unmount", function(e, t) {for (var s in this.props) if (!(s in e)) return !0;return !1;};-function kt(e, t) {- return Re(function() {- return pt(e, t);+function jt(e, t) {+ return Le(function() {+ return gt(e, t);}, []);}-var At = function(e) {+var Mt = function(e) {queueMicrotask(function() {queueMicrotask(e);});};-function jt() {- at(function() {- for (var e; e = Tt.shift();) St.call(e);+function Nt() {+ ot(function() {+ for (var e; e = Dt.shift();) wt.call(e);});}-function Mt() {- Tt.push(this) === 1 && (f.requestAnimationFrame || At)(jt);+function Pt() {+ Dt.push(this) === 1 && (f.requestAnimationFrame || Mt)(Nt);}//#endregion//#region src/state/quality-goals.ts-var Nt = "/api/quality-goals?limit=200", Pt = {+var Ft = "/api/quality-goals?limit=200", It = {data: null,error: ""-}, Ft = pt(Pt), It = 0, Lt = _t(() => Ft.value);-_t(() => Ft.value.data?.total ?? null);-function Rt() {- It += 1, Ft.value = Pt;+}, Lt = gt(It), Rt = 0, zt = bt(() => Lt.value);+bt(() => Lt.value.data?.total ?? null);+function Bt() {+ Rt += 1, Lt.value = It;}-async function zt(e) {- let t = It += 1;+async function Vt(e) {+ let t = Rt += 1;try {- let n = await I(Nt, e);- return t === It && (Ft.value = {+ let n = await I(Ft, e);+ return t === Rt && (Lt.value = {data: n,error: ""}), n;} catch (n) {- throw !e?.aborted && t === It && (Ft.value = {+ throw !e?.aborted && t === Rt && (Lt.value = {data: null,error: F(n)}), n;@@ -1331,10 +1463,10 @@ async function zt(e) {}//#endregion//#region src/islands/quality-goals.tsx-var Bt = (e, t) => zt(t), Vt = (e) => e.has_cover ? `/cover?code=${encodeURIComponent(e.code ?? "")}` : `/poster?id=${e.id}&c=4`;-function Ht({ openItem: e, javTitleHtml: n, javDisplayName: i, srcBadge: a }) {- let { data: o, error: s } = Lt.value;- if (s) return /* @__PURE__ */ U("div", {+var Ht = (e, t) => Vt(t), Ut = (e) => e.has_cover ? `/cover?code=${encodeURIComponent(e.code ?? "")}` : `/poster?id=${e.id}&c=4`;+function Wt({ openItem: e, javTitleHtml: n, javDisplayName: i, srcBadge: a }) {+ let { data: o, error: s } = zt.value;+ if (s) return /* @__PURE__ */ W("div", {class: "qualitylist",dangerouslySetInnerHTML: { __html: r(s, {variant: "error",@@ -1342,51 +1474,51 @@ function Ht({ openItem: e, javTitleHtml: n, javDisplayName: i, srcBadge: a }) {}) }});let d = o?.items ?? [];- return d.length ? /* @__PURE__ */ U("div", {+ return d.length ? /* @__PURE__ */ W("div", {class: "qualitylist",- children: d.map((t) => /* @__PURE__ */ U("article", {+ children: d.map((t) => /* @__PURE__ */ W("article", {class: "qualityitem",- children: [/* @__PURE__ */ U("button", {+ children: [/* @__PURE__ */ W("button", {class: "qualitycover",type: "button","aria-label": `打开 ${i(t)}`,onClick: () => e(t.id),- children: /* @__PURE__ */ U("img", {- src: Vt(t),+ children: /* @__PURE__ */ W("img", {+ src: Ut(t),alt: "",loading: "lazy",onError: (e) => e.currentTarget.remove()})- }), /* @__PURE__ */ U("div", { children: [- /* @__PURE__ */ U("h3", { children: /* @__PURE__ */ U("button", {+ }), /* @__PURE__ */ W("div", { children: [+ /* @__PURE__ */ W("h3", { children: /* @__PURE__ */ W("button", {type: "button","data-middle-truncate": !0,onClick: () => e(t.id),dangerouslySetInnerHTML: { __html: n(t) }}) }),- /* @__PURE__ */ U("p", {+ /* @__PURE__ */ W("p", {class: "mono",children: [- /* @__PURE__ */ U("span", {+ /* @__PURE__ */ W("span", {style: "display:contents",dangerouslySetInnerHTML: { __html: a(t.location, t.cost) }}),- /* @__PURE__ */ U("span", { children: c[t.location] ?? t.location }),- /* @__PURE__ */ U("span", { children: l(t.duration) }),- /* @__PURE__ */ U("span", { children: u(t.size ?? 0) })+ /* @__PURE__ */ W("span", { children: c[t.location] ?? t.location }),+ /* @__PURE__ */ W("span", { children: l(t.duration) }),+ /* @__PURE__ */ W("span", { children: u(t.size ?? 0) })]}),- t.reason ? /* @__PURE__ */ U("p", { children: t.reason }) : null+ t.reason ? /* @__PURE__ */ W("p", { children: t.reason }) : null] })]}, t.id))- }) : /* @__PURE__ */ U("div", {+ }) : /* @__PURE__ */ W("div", {class: "qualitylist",dangerouslySetInnerHTML: { __html: t("sparkles", "没有标记中的高清版目标", "现有版本都已满足条件,或还没有加入追踪。") }});}//#endregion//#region src/jobs.ts-async function Ut(e) {+async function Gt(e) {let t = e.pause || ((e) => new Promise((t) => setTimeout(t, e))), n = 0;for (; e.active();) {let r;@@ -1401,11 +1533,11 @@ async function Ut(e) {await t(2e3);}}-function Wt(e) {+function Kt(e) {let t = document.createElement("div");e.host.hidden = !0, t.dataset.followJob = "", t.setAttribute("aria-live", "polite"), e.host.prepend(t);let n = e.storageKey || "peach-follow-job", r = sessionStorage.getItem(n) || void 0, i = !1;- Ut({+ Gt({read: e.read,active: () => !i && e.active() && t.isConnected,keepWatching: e.watchIdle !== !1,@@ -1431,10 +1563,10 @@ function Wt(e) {}//#endregion//#region src/islands/scraping.tsx-var Gt = (e, t) => I("/api/scraping", t);-function Kt({ value: e, onChange: t }) {- let n = H(null), r = H(t);- return r.current = t, V(() => {+var qt = (e, t) => I("/api/scraping", t);+function Jt({ value: e, onChange: t }) {+ let n = U(null), r = U(t);+ return r.current = t, H(() => {let t = n.current;t.innerHTML = i([["environment", "系统代理"],@@ -1445,27 +1577,27 @@ function Kt({ value: e, onChange: t }) {return a.addEventListener("change", o), () => {a.disabled = !0, a.removeEventListener("change", o), t.replaceChildren();};- }, []), /* @__PURE__ */ U("div", {+ }, []), /* @__PURE__ */ W("div", {ref: n,class: "scraping-network"});}-function qt({ source: e, toast: t }) {- let [i, a] = B(e), [s, c] = B(e.network), [l, u] = B(""), [d, f] = B(""), [p, m] = B(""), [h, g] = B("paste"), [_, v] = B(""), [y, b] = B(!1), [x, S] = B(""), [C, w] = B([]), T = H(null), E = H(null);- V(() => {+function Yt({ source: e, toast: t }) {+ let [i, a] = V(e), [s, c] = V(e.network), [l, u] = V(""), [d, f] = V(""), [p, m] = V(""), [h, g] = V("paste"), [_, v] = V(""), [y, b] = V(!1), [x, S] = V(""), [C, w] = V([]), T = U(null), E = U(null);+ H(() => {E.current?.querySelectorAll("footer button").forEach((e) => o(e, y));}, [y]);- let D = H(new AbortController());- Le(() => () => D.current.abort(), []);+ let D = U(new AbortController());+ Ie(() => () => D.current.abort(), []);async function O(n) {if (!y) {b(!0), S(""), w([]);try {if (n === "check") {- let t = await we("/api/scraping/check", { source: e.source }, "POST", D.current.signal);+ let t = await L("/api/scraping/check", { source: e.source }, "POST", D.current.signal);D.current.signal.aborted || w(t.results);} else {- let r = await we("/api/scraping/settings", {+ let r = await L("/api/scraping/settings", {source: e.source,network: s,proxy: l,@@ -1482,34 +1614,34 @@ function qt({ source: e, toast: t }) {}}}- return /* @__PURE__ */ U("section", {+ return /* @__PURE__ */ W("section", {class: "scraping-source",- children: /* @__PURE__ */ U("form", {+ children: /* @__PURE__ */ W("form", {ref: E,class: "cleanupfieldset","data-geist-fieldset": !0,onSubmit: (e) => {e.preventDefault(), O("save");},- children: [/* @__PURE__ */ U("div", {+ children: [/* @__PURE__ */ W("div", {class: "geist-fieldset-content scraping-fields",children: [- /* @__PURE__ */ U("div", { dangerouslySetInnerHTML: { __html: n(`scraping-${e.source}`, e.label) } }),- /* @__PURE__ */ U("a", {+ /* @__PURE__ */ W("div", { dangerouslySetInnerHTML: { __html: n(`scraping-${e.source}`, e.label) } }),+ /* @__PURE__ */ W("a", {class: "scraping-url",href: e.login,target: "_blank",rel: "noopener noreferrer",children: e.login}),- /* @__PURE__ */ U("div", {+ /* @__PURE__ */ W("div", {class: "scraping-label",- children: ["连接方式", /* @__PURE__ */ U(Kt, {+ children: ["连接方式", /* @__PURE__ */ W(Jt, {value: s,onChange: c})]}),- s === "proxy" && /* @__PURE__ */ U("label", { children: ["代理地址", /* @__PURE__ */ U("input", {+ s === "proxy" && /* @__PURE__ */ W("label", { children: ["代理地址", /* @__PURE__ */ W("input", {class: "geist-input",type: "password",autoComplete: "off",@@ -1518,13 +1650,13 @@ function qt({ source: e, toast: t }) {disabled: y,onInput: (e) => u(e.currentTarget.value)})] }),- e.accepts_cookie && /* @__PURE__ */ U(M, { children: [- /* @__PURE__ */ U("p", { children: i.cookie_saved ? "Cookie 已保存,登录是否有效请在抓取时确认。" : "需要登录时,任选一种方式提供 Cookie。" }),- /* @__PURE__ */ U("div", {+ e.accepts_cookie && /* @__PURE__ */ W(M, { children: [+ /* @__PURE__ */ W("p", { children: i.cookie_saved ? "Cookie 已保存,登录是否有效请在抓取时确认。" : "需要登录时,任选一种方式提供 Cookie。" }),+ /* @__PURE__ */ W("div", {class: "insightswitch scraping-cookie-method",role: "radiogroup","aria-label": "提供 Cookie 的方式(二选一)",- children: [["paste", "粘贴 Cookie"], ["file", "导入文件"]].map(([t, n]) => /* @__PURE__ */ U("label", { children: [/* @__PURE__ */ U("input", {+ children: [["paste", "粘贴 Cookie"], ["file", "导入文件"]].map(([t, n]) => /* @__PURE__ */ W("label", { children: [/* @__PURE__ */ W("input", {type: "radio",name: `cookie-method-${e.source}`,value: t,@@ -1532,29 +1664,29 @@ function qt({ source: e, toast: t }) {onChange: () => {g(t), f(""), m(""), v("");}- }), /* @__PURE__ */ U("span", { children: n })] }, t))+ }), /* @__PURE__ */ W("span", { children: n })] }, t))}),- h === "paste" ? /* @__PURE__ */ U("label", { children: ["Cookie", /* @__PURE__ */ U("input", {+ h === "paste" ? /* @__PURE__ */ W("label", { children: ["Cookie", /* @__PURE__ */ W("input", {class: "geist-input",type: "password",autoComplete: "off",value: d,disabled: y,onInput: (e) => f(e.currentTarget.value)- })] }) : /* @__PURE__ */ U("label", {+ })] }) : /* @__PURE__ */ W("label", {class: "scraping-file",- children: ["Netscape Cookie 文件(.txt)", /* @__PURE__ */ U("span", {+ children: ["Netscape Cookie 文件(.txt)", /* @__PURE__ */ W("span", {class: "scraping-file-control",children: [- /* @__PURE__ */ U("span", {+ /* @__PURE__ */ W("span", {class: "geist-button",children: "选择文件"}),- /* @__PURE__ */ U("span", {+ /* @__PURE__ */ W("span", {class: "scraping-file-name",children: _ || "未选择文件"}),- /* @__PURE__ */ U("input", {+ /* @__PURE__ */ W("input", {ref: T,type: "file",accept: ".txt",@@ -1584,31 +1716,31 @@ function qt({ source: e, toast: t }) {})]})] }),- x && /* @__PURE__ */ U("div", {+ x && /* @__PURE__ */ W("div", {role: "alert",dangerouslySetInnerHTML: { __html: r(x, { variant: "error" }) }}),- C.map((t) => /* @__PURE__ */ U("div", {+ C.map((t) => /* @__PURE__ */ W("div", {role: "status",dangerouslySetInnerHTML: { __html: r(`${e.label}${t.label === "来源页面" ? "" : " 高清图片"}:${t.ok ? "可连接" : "不能连接"}` + (t.width ? ` · ${t.width} × ${t.height}` : "") + (t.message ? `。${t.message}` : ""), { variant: t.ok ? "success" : "error" }) }}, t.label))]- }), /* @__PURE__ */ U("footer", {+ }), /* @__PURE__ */ W("footer", {class: "geist-fieldset-footer","data-geist-fieldset-footer": !0,children: [- /* @__PURE__ */ U("button", {+ /* @__PURE__ */ W("button", {class: "geist-button primary",type: "submit",children: "保存"}),- /* @__PURE__ */ U("button", {+ /* @__PURE__ */ W("button", {class: "geist-button",type: "button",onClick: () => void O("check"),children: "检查连接"}),- e.accepts_cookie && i.cookie_saved && /* @__PURE__ */ U("button", {+ e.accepts_cookie && i.cookie_saved && /* @__PURE__ */ W("button", {class: "geist-button",type: "button",onClick: () => void O("revoke"),@@ -1619,13 +1751,13 @@ function qt({ source: e, toast: t }) {})});}-function Jt({ data: e, error: t, toast: i }) {- let [a, s] = B(""), [c, l] = B(!1), [u, d] = B(""), f = H(null);- V(() => o(f.current, c), [c]);- let p = H(new AbortController()), m = H(0);+function Xt({ data: e, error: t, toast: i }) {+ let [a, s] = V(""), [c, l] = V(!1), [u, d] = V(""), f = U(null);+ H(() => o(f.current, c), [c]);+ let p = U(new AbortController()), m = U(0);async function h(e = !1) {let t = ++m.current;- await Ut({+ await Gt({read: (e) => I("/api/scraping/cover", e),active: () => !p.current.signal.aborted && t === m.current,render: (t) => {@@ -1634,37 +1766,37 @@ function Jt({ data: e, error: t, toast: i }) {disconnected: () => d("连接中断,正在重新读取后台进度")});}- Le(() => (h(!0), () => p.current.abort()), []);+ Ie(() => (h(!0), () => p.current.abort()), []);async function g() {if (!c) {m.current++, l(!0), d("");try {- await we("/api/scraping/cover", { code: a }, "POST", p.current.signal), await h();+ await L("/api/scraping/cover", { code: a }, "POST", p.current.signal), await h();} catch (e) {p.current.signal.aborted || (l(!1), d(F(e)));}}}- return t ? /* @__PURE__ */ U("div", {+ return t ? /* @__PURE__ */ W("div", {role: "alert",dangerouslySetInnerHTML: { __html: r(t, { variant: "error" }) }- }) : /* @__PURE__ */ U("div", {+ }) : /* @__PURE__ */ W("div", {class: "scraping-page",children: [- /* @__PURE__ */ U("p", { children: "高清图片可能需要代理才能下载,请先检查连接。" }),- /* @__PURE__ */ U("section", {+ /* @__PURE__ */ W("p", { children: "高清图片可能需要代理才能下载,请先检查连接。" }),+ /* @__PURE__ */ W("section", {class: "cleanupfieldset scraping-source","data-geist-fieldset": !0,- children: /* @__PURE__ */ U("div", {+ children: /* @__PURE__ */ W("div", {class: "geist-fieldset-content scraping-fields",children: [- /* @__PURE__ */ U("div", { dangerouslySetInnerHTML: { __html: n("scraping-cover", "高清封面") } }),- /* @__PURE__ */ U("form", {+ /* @__PURE__ */ W("div", { dangerouslySetInnerHTML: { __html: n("scraping-cover", "高清封面") } }),+ /* @__PURE__ */ W("form", {class: "scraping-cover-form",onSubmit: (e) => {e.preventDefault(), g();},- children: [/* @__PURE__ */ U("input", {+ children: [/* @__PURE__ */ W("input", {class: "geist-input","aria-label": "馆藏番号",required: !0,@@ -1672,21 +1804,21 @@ function Jt({ data: e, error: t, toast: i }) {disabled: c,placeholder: "输入馆藏番号,如 ABW-232",onInput: (e) => s(e.currentTarget.value)- }), /* @__PURE__ */ U("button", {+ }), /* @__PURE__ */ W("button", {ref: f,class: "geist-button primary",type: "submit",children: "抓取封面"})]}),- u && /* @__PURE__ */ U("div", {+ u && /* @__PURE__ */ W("div", {role: "alert",dangerouslySetInnerHTML: { __html: r(u, { variant: "error" }) }})]})}),- e?.sources.map((e) => /* @__PURE__ */ U(qt, {+ e?.sources.map((e) => /* @__PURE__ */ W(Yt, {source: e,toast: i}, e.source))@@ -1695,12 +1827,12 @@ function Jt({ data: e, error: t, toast: i }) {}//#endregion//#region src/state/index.ts-var Yt = { "quality-goals": {- refresh: zt,- reset: Rt-} }, Xt = () => Object.keys(Yt);-async function Zt(e) {- let t = Yt[e];+var Zt = { "quality-goals": {+ refresh: Vt,+ reset: Bt+} }, Qt = () => Object.keys(Zt);+async function $t(e) {+ let t = Zt[e];if (!t) throw Error(`未登记的共享 store:${String(e)}`);try {return await t.refresh(), !0;@@ -1710,10 +1842,10 @@ async function Zt(e) {}//#endregion//#region src/native-image.ts-function Qt(e, t, n, r) {+function en(e, t, n, r) {return e > 0 && t > 0 && e === n && t === r;}-function $t(e, t, n, r, i = 1) {+function tn(e, t, n, r, i = 1) {let a = Number.isFinite(i) && i > 0 ? i : 1;e /= a, t /= a;let o = [@@ -1730,7 +1862,7 @@ function $t(e, t, n, r, i = 1) {}//#endregion//#region src/entity-skeleton.ts-function en(e, t) {+function nn(e, t) {return `<section data-skeleton="entity/${e}" role="status" aria-label="正在读取资料"><span class="sr-only">正在读取资料</span><div aria-hidden="true"><div class="entityhero"><div class="entityportrait ${e === "studio" || e === "agency" ? "square " : ""}skeleton"></div>@@ -1742,7 +1874,7 @@ function en(e, t) {}//#endregion//#region src/sidebar.ts-function tn(e) {+function rn(e) {return ["/","/unseen",@@ -1752,23 +1884,23 @@ function tn(e) {"/junk-files"].includes(e) || /^\/(item|mix|parts|editions)\//.test(e) || /^\/playlists\/\d+\/\d+$/.test(e) || /^\/(performers|studios|creators|series|agencies)\/.+/.test(e);}-function nn(e, t) {+function an(e, t) {return e.dataset.surface === t && e.querySelector(".dnav") ? !1 : (e.dataset.surface = t, e.replaceChildren(), !0);}-function rn(e) {+function on(e) {let t = /* @__PURE__ */ new Map();for (let n of e) for (let e of new Set(n.tags || [])) t.set(e, (t.get(e) || 0) + 1);return [...t].sort((e, t) => t[1] - e[1]).slice(0, 30);}//#endregion//#region src/management.ts-function an(e) {+function sn(e) {return e.filter((e) => ["115", "pikpak"].includes(e.location) && (e.roots === void 0 || e.roots.length > 0)).map((e) => e.location);}-function on(e, t) {+function cn(e, t) {return t.filter((t) => e.some((e) => e.location === t));}-function sn() {+function ln() {return `<div class="cleanuppage" data-skeleton="cleanup" aria-busy="true" aria-label="正在读取数据管理状态"><div class="cleanupgrid">${[[@@ -1814,7 +1946,7 @@ function sn() {<footer class="geist-fieldset-footer" data-geist-fieldset-footer><button type="button"${r === 3 ? " class=\"danger\"" : ""} disabled>${r === 3 ? "<svg aria-hidden=\"true\"><use href=\"#i-trash\"></use></svg><span>" + t + "</span>" : t}</button></footer></section>`).join("")}</div></div>`;}-function cn(e, t = !1, n = !1) {+function un(e, t = !1, n = !1) {if (t || n) return "";let r = "<svg aria-hidden=\"true\"><use href=\"#i-external-link\"></use></svg>";return `<details class="taste-history-guide"${e ? " open" : ""}>@@ -1828,60 +1960,60 @@ function cn(e, t = !1, n = !1) {<button type="button" class="taste-guide-skip">跳过</button></div></details>`;}-var ln = "peach-taste-guide-dismissed";-function un(e, t) {+var dn = "peach-taste-guide-dismissed";+function fn(e, t) {let n = e.querySelector(".taste-history-guide");n?.querySelector(".taste-guide-skip")?.addEventListener("click", () => {- t.setItem(ln, "1"), n.remove();+ t.setItem(dn, "1"), n.remove();});}//#endregion//#region src/jav-artwork.ts-function dn(e) {+function pn(e) {return ["small","sleeve","preview"].includes(String(e)) ? "small" : "big";}-function fn(e) {+function mn(e) {return {- javLayout: dn(e.javLayout),- javImage: pn(e.javLayout === "preview" ? "thumbnail" : e.javImage)+ javLayout: pn(e.javLayout),+ javImage: hn(e.javLayout === "preview" ? "thumbnail" : e.javImage)};}-function pn(e) {+function hn(e) {return e === "thumbnail" ? "thumbnail" : "cover";}-function mn(e, t) {- return e.is_jav && e.code && e.has_cover && (pn(t) === "cover" || !e.has_thumb) ? "cover" : e.has_thumb ? "thumbnail" : "";+function gn(e, t) {+ return e.is_jav && e.code && e.has_cover && (hn(t) === "cover" || !e.has_thumb) ? "cover" : e.has_thumb ? "thumbnail" : "";}-function hn(e, t) {+function _n(e, t) {e.querySelectorAll("img[data-jav-image]").forEach((e) => {- let n = e.dataset.javCover || "", r = e.dataset.javThumb || "", i = !!(n && (pn(t) === "cover" || !r)), a = i ? n : r;+ let n = e.dataset.javCover || "", r = e.dataset.javThumb || "", i = !!(n && (hn(t) === "cover" || !r)), a = i ? n : r;e.classList.toggle("cover", i), e.classList.toggle("whole", i && e.dataset.javImageLayout !== "big"), e.classList.toggle("front", i && e.dataset.javImageLayout === "big"), e.removeAttribute("style"), a && e.getAttribute("src") !== a && (e.src = a);});}//#endregion//#region src/islands.ts-var gn = {+var vn = {scraping: {- load: Gt,- component: Jt+ load: qt,+ component: Xt},"quality-goals": {- load: Bt,- component: Ht+ load: Ht,+ component: Wt},configuration: {- load: Xe,- component: nt+ load: Ze,+ component: rt}-}, _n = () => Object.keys(gn), $ = /* @__PURE__ */ new Map();-async function vn(e, t, n, r = {}) {- let i = gn[e];+}, yn = () => Object.keys(vn), $ = /* @__PURE__ */ new Map();+async function bn(e, t, n, r = {}) {+ let i = vn[e];if (!i) throw Error(`未注册的 island:${String(e)}`);- yn(t);+ xn(t);let a = {controller: new AbortController(),painted: !1@@ -1912,9 +2044,9 @@ async function vn(e, t, n, r = {}) {};xe(te(i.component, s), t);}-function yn(e) {+function xn(e) {let t = $.get(e);t && (t.controller.abort(), $.delete(e), t.painted && xe(null, e));}//#endregion-export { ln as TASTE_GUIDE_KEY, sn as cleanupSkeletonHtml, an as cloudLocations, on as cloudPreferenceLocations, en as entitySkeletonHtml, Wt as followJobProgress, _n as islandNames, mn as javImageKind, Qt as matchesFaceSource, vn as mountIsland, $t as nativeImageFit, pn as normalizeJavImage, dn as normalizeJavLayout, fn as normalizeJavPreferences, Zt as refreshStore, tn as sidebarHasCatalogContent, rn as sidebarTagCounts, Xt as storeNames, hn as syncJavImages, nn as syncSidebarSurface, cn as tasteHistoryGuideHtml, yn as unmountIsland, Ut as watchJob, un as wireTasteHistoryGuide };+export { dn as TASTE_GUIDE_KEY, ln as cleanupSkeletonHtml, sn as cloudLocations, cn as cloudPreferenceLocations, nn as entitySkeletonHtml, Kt as followJobProgress, yn as islandNames, gn as javImageKind, en as matchesFaceSource, bn as mountIsland, tn as nativeImageFit, hn as normalizeJavImage, pn as normalizeJavLayout, mn as normalizeJavPreferences, $t as refreshStore, rn as sidebarHasCatalogContent, on as sidebarTagCounts, Qt as storeNames, _n as syncJavImages, an as syncSidebarSurface, un as tasteHistoryGuideHtml, xn as unmountIsland, Gt as watchJob, fn as wireTasteHistoryGuide };