From d5937e168f30bfbdc3ee7fc2f0739be665de31de Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:54:08 +0800 Subject: [PATCH 1/2] tw-pack: configuration pack format and the item model A new crate for the .twconfig configuration pack that export, sharing, local backups and sync versions share: - Format: a ZIP with manifest.json, config.yaml, plugin scripts and their approved copies, and client-prefs.json; optionally sealed with age (scrypt passphrase, or an X25519 recipient for sync). Reading treats the file as untrusted: size limits on the file and on what it unpacks to, only the known paths, valid plugin ids, no duplicates. Errors carry their own message codes (pack.*). Same content writes the same bytes. - Model: a configuration split into items (upstreams, proxies, keys, aliases, groups, routes, price sheets, custom security rules, plugins, the order of upstreams, routes and plugins, each global section, client preferences) and merge units (upstream: conn/models/billing/other; plugin: script/settings/enabled; global settings and preferences field by field). Values are normalized, so comments, layout and written-out defaults are not differences. Local settings (listen, retention, sync, the ChatGPT login and account header, the script of a shipped default plugin) stay out of the snapshot and are kept on materialize. - materialize: lands a target snapshot on a local config by editing it item by item, so untouched items keep their bytes and comments; falls back to a full rewrite when an edit cannot apply, and verifies the result either way. A plugin that can rewrite tool calls is not approved when it arrives enabled from elsewhere. - rename follows every reference; content_id identifies the shareable content (12 hex chars of blake3 over the normalized snapshot). Plugin source splitting needs the plugin runtime, which this crate does not depend on; the core installs it (install_codec), and without it a script is compared whole. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 682 +++++++++++++++++-- Cargo.toml | 9 + README.md | 1 + README.zh-CN.md | 1 + crates/tw-api/msg-codes.txt | 12 + crates/tw-pack/Cargo.toml | 30 + crates/tw-pack/src/lib.rs | 696 +++++++++++++++++++ crates/tw-pack/src/model/codec.rs | 47 ++ crates/tw-pack/src/model/items.rs | 728 ++++++++++++++++++++ crates/tw-pack/src/model/json.rs | 131 ++++ crates/tw-pack/src/model/mod.rs | 533 +++++++++++++++ crates/tw-pack/src/model/rename.rs | 241 +++++++ crates/tw-pack/src/model/tests.rs | 1015 ++++++++++++++++++++++++++++ crates/tw-pack/src/model/write.rs | 799 ++++++++++++++++++++++ crates/tw-pack/src/tests.rs | 334 +++++++++ 15 files changed, 5221 insertions(+), 38 deletions(-) create mode 100644 crates/tw-pack/Cargo.toml create mode 100644 crates/tw-pack/src/lib.rs create mode 100644 crates/tw-pack/src/model/codec.rs create mode 100644 crates/tw-pack/src/model/items.rs create mode 100644 crates/tw-pack/src/model/json.rs create mode 100644 crates/tw-pack/src/model/mod.rs create mode 100644 crates/tw-pack/src/model/rename.rs create mode 100644 crates/tw-pack/src/model/tests.rs create mode 100644 crates/tw-pack/src/model/write.rs create mode 100644 crates/tw-pack/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index aa6d27e0..236aa92c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -27,6 +27,49 @@ dependencies = [ "generic-array", ] +[[package]] +name = "age" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "047a482d1843edf1ce76ada63183698144030fe1191bd5ddba6e41e164e0bc43" +dependencies = [ + "age-core", + "base64 0.21.7", + "bech32", + "chacha20poly1305", + "cookie-factory", + "hmac 0.12.1", + "i18n-embed", + "i18n-embed-fl", + "lazy_static", + "nom", + "pin-project", + "rand 0.8.8", + "rust-embed", + "scrypt", + "sha2 0.10.9", + "subtle", + "x25519-dalek", + "zeroize", +] + +[[package]] +name = "age-core" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2bf6a89c984ca9d850913ece2da39e1d200563b0a94b002b253beee4c5acf99" +dependencies = [ + "base64 0.21.7", + "chacha20poly1305", + "cookie-factory", + "hkdf", + "io_tee", + "nom", + "rand 0.8.8", + "secrecy", + "sha2 0.10.9", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -227,7 +270,7 @@ dependencies = [ "bytes", "form_urlencoded", "hex", - "hmac", + "hmac 0.13.0", "http", "percent-encoding", "sha2 0.11.0", @@ -335,7 +378,7 @@ checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", "axum-macros", - "base64", + "base64 0.22.1", "bytes", "form_urlencoded", "futures-util", @@ -394,6 +437,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + [[package]] name = "base64" version = "0.22.1" @@ -410,6 +459,21 @@ dependencies = [ "vsimd", ] +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + +[[package]] +name = "bech32" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d86b93f97252c47b41663388e6d155714a9d0c398b99f1005cbc5f978b29f445" + [[package]] name = "bitflags" version = "2.13.1" @@ -626,7 +690,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" dependencies = [ - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -657,6 +721,15 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" +dependencies = [ + "futures", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -761,7 +834,7 @@ dependencies = [ "postcard", "pulley-interpreter", "regalloc2", - "rustc-hash", + "rustc-hash 2.1.3", "serde", "serde_derive", "sha2 0.10.9", @@ -920,6 +993,7 @@ dependencies = [ "fiat-crypto", "rustc_version", "subtle", + "zeroize", ] [[package]] @@ -1043,6 +1117,15 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "find-crate" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59a98bbaacea1c0eb6a0876280051b892eb73594fd90cf3b20e9c817029c57d2" +dependencies = [ + "toml", +] + [[package]] name = "find-msvc-tools" version = "0.1.12" @@ -1060,6 +1143,50 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "fluent" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb74634707bebd0ce645a981148e8fb8c7bccd4c33c652aeffd28bf2f96d555a" +dependencies = [ + "fluent-bundle", + "unic-langid", +] + +[[package]] +name = "fluent-bundle" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fe0a21ee80050c678013f82edf4b705fe2f26f1f9877593d13198612503f493" +dependencies = [ + "fluent-langneg", + "fluent-syntax", + "intl-memoizer", + "intl_pluralrules", + "rustc-hash 1.1.0", + "self_cell 0.10.3", + "smallvec", + "unic-langid", +] + +[[package]] +name = "fluent-langneg" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eebbe59450baee8282d71676f3bfed5689aeab00b27545e83e5f14b1195e8b0" +dependencies = [ + "unic-langid", +] + +[[package]] +name = "fluent-syntax" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a530c4694a6a8d528794ee9bbd8ba0122e779629ac908d15ad5a7ae7763a33d" +dependencies = [ + "thiserror 1.0.69", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1305,6 +1432,24 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac 0.12.1", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "hmac" version = "0.13.0" @@ -1411,7 +1556,7 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-channel", "futures-util", @@ -1428,6 +1573,72 @@ dependencies = [ "tracing", ] +[[package]] +name = "i18n-config" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e06b90c8a0d252e203c94344b21e35a30f3a3a85dc7db5af8f8df9f3e0c63ef" +dependencies = [ + "basic-toml", + "log", + "serde", + "serde_derive", + "thiserror 1.0.69", + "unic-langid", +] + +[[package]] +name = "i18n-embed" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "669ffc2c93f97e6ddf06ddbe999fcd6782e3342978bb85f7d3c087c7978404c4" +dependencies = [ + "arc-swap", + "fluent", + "fluent-langneg", + "fluent-syntax", + "i18n-embed-impl", + "intl-memoizer", + "log", + "parking_lot", + "rust-embed", + "thiserror 1.0.69", + "unic-langid", + "walkdir", +] + +[[package]] +name = "i18n-embed-fl" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04b2969d0b3fc6143776c535184c19722032b43e6a642d710fa3f88faec53c2d" +dependencies = [ + "find-crate", + "fluent", + "fluent-syntax", + "i18n-config", + "i18n-embed", + "proc-macro-error2", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", + "unic-langid", +] + +[[package]] +name = "i18n-embed-impl" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2cc0e0523d1fe6fc2c6f66e5038624ea8091b3e7748b5e8e0c84b1698db6c2" +dependencies = [ + "find-crate", + "i18n-config", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -1597,6 +1808,31 @@ dependencies = [ "generic-array", ] +[[package]] +name = "intl-memoizer" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "310da2e345f5eb861e7a07ee182262e94975051db9e4223e909ba90f392f163f" +dependencies = [ + "type-map", + "unic-langid", +] + +[[package]] +name = "intl_pluralrules" +version = "7.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" +dependencies = [ + "unic-langid", +] + +[[package]] +name = "io_tee" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b3f7cef34251886990511df1c61443aa928499d598a9473929ab5a90a527304" + [[package]] name = "ipnet" version = "2.12.2" @@ -1636,7 +1872,7 @@ dependencies = [ "jni-sys", "log", "simd_cesu8", - "thiserror", + "thiserror 2.0.20", "walkdir", "windows-link", ] @@ -1761,6 +1997,15 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -1815,6 +2060,22 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -1837,6 +2098,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "notify" version = "8.2.0" @@ -1939,12 +2210,65 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac 0.12.1", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -2010,6 +2334,28 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2053,10 +2399,10 @@ dependencies = [ "pin-project-lite", "quinn-proto", "quinn-udp", - "rustc-hash", + "rustc-hash 2.1.3", "rustls", "socket2", - "thiserror", + "thiserror 2.0.20", "tokio", "tracing", "web-time", @@ -2075,11 +2421,11 @@ dependencies = [ "rand 0.10.2", "rand_pcg", "ring", - "rustc-hash", + "rustc-hash 2.1.3", "rustls", "rustls-pki-types", "slab", - "thiserror", + "thiserror 2.0.20", "tinyvec", "tracing", "web-time", @@ -2120,13 +2466,24 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha", + "rand_chacha 0.9.0", "rand_core 0.9.5", ] @@ -2141,6 +2498,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_chacha" version = "0.9.0" @@ -2151,6 +2518,15 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "rand_core" version = "0.9.5" @@ -2195,6 +2571,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + [[package]] name = "regalloc2" version = "0.15.2" @@ -2205,7 +2590,7 @@ dependencies = [ "bumpalo", "hashbrown 0.17.1", "log", - "rustc-hash", + "rustc-hash 2.1.3", "serde", "smallvec", ] @@ -2245,7 +2630,7 @@ version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-core", "futures-util", @@ -2302,7 +2687,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" dependencies = [ "hashbrown 0.16.1", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -2320,12 +2705,53 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "rust-embed" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053" +dependencies = [ + "mime_guess", + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.119", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a" +dependencies = [ + "sha2 0.11.0", + "walkdir", +] + [[package]] name = "rustc-demangle" version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2442,6 +2868,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher", +] + [[package]] name = "same-file" version = "1.0.6" @@ -2458,7 +2893,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0b1b76852c5643f558e7347e4de549474c3ecb7154295a189f4668428c1b453" dependencies = [ "arraydeque", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -2470,6 +2905,32 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2", + "salsa20", + "sha2 0.10.9", +] + +[[package]] +name = "secrecy" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" +dependencies = [ + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -2493,6 +2954,21 @@ dependencies = [ "libc", ] +[[package]] +name = "self_cell" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14e4d63b804dc0c7ec4a1e52bcb63f02c7ac94476755aa579edac21e01f915d" +dependencies = [ + "self_cell 1.3.0", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + [[package]] name = "semver" version = "1.0.28" @@ -2786,7 +3262,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys 0.61.2", @@ -2801,13 +3277,33 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -2867,6 +3363,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] @@ -2972,6 +3469,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +dependencies = [ + "serde", +] + [[package]] name = "tower" version = "0.5.3" @@ -3092,7 +3598,7 @@ version = "12.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8" dependencies = [ - "thiserror", + "thiserror 2.0.20", "ts-rs-macros", ] @@ -3121,7 +3627,7 @@ dependencies = [ "log", "rand 0.9.5", "sha1", - "thiserror", + "thiserror 2.0.20", "utf-8", ] @@ -3138,7 +3644,7 @@ dependencies = [ "log", "rand 0.9.5", "sha1", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -3164,7 +3670,7 @@ dependencies = [ "bytes", "futures", "hex", - "hmac", + "hmac 0.13.0", "percent-encoding", "reqwest", "serde_json", @@ -3192,7 +3698,7 @@ dependencies = [ "serde", "serde_yaml_ng", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tw-api", "tw-bedrock", @@ -3211,7 +3717,7 @@ name = "tw-control" version = "0.76.0" dependencies = [ "axum", - "base64", + "base64 0.22.1", "bytes", "chrono", "futures", @@ -3226,7 +3732,7 @@ dependencies = [ "serde_yaml_ng", "sha2 0.11.0", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-stream", "tokio-tungstenite 0.28.0", @@ -3266,7 +3772,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml_ng", - "thiserror", + "thiserror 2.0.20", "tracing", "tw-dialect", "tw-types", @@ -3281,7 +3787,7 @@ dependencies = [ "aws-smithy-eventstream", "aws-smithy-types", "axum", - "base64", + "base64 0.22.1", "blake3", "bytes", "chrono", @@ -3301,7 +3807,7 @@ dependencies = [ "serde_yaml_ng", "sha2 0.11.0", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-rustls", "tokio-tungstenite 0.28.0", @@ -3328,7 +3834,7 @@ name = "tw-guard" version = "0.76.0" dependencies = [ "aho-corasick", - "base64", + "base64 0.22.1", "bytes", "memchr", "regex", @@ -3336,7 +3842,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml_ng", - "thiserror", + "thiserror 2.0.20", "ts-rs", "tw-dialect", ] @@ -3349,7 +3855,7 @@ dependencies = [ "serde_json", "snow", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tw-api", "tw-yaml", @@ -3364,6 +3870,26 @@ dependencies = [ "tw-api", ] +[[package]] +name = "tw-pack" +version = "0.76.0" +dependencies = [ + "age", + "blake3", + "serde", + "serde_json", + "serde_yaml_ng", + "sha2 0.11.0", + "tempfile", + "thiserror 2.0.20", + "tw-config", + "tw-engine", + "tw-pricing", + "tw-types", + "tw-yaml", + "zip", +] + [[package]] name = "tw-plugin" version = "0.76.0" @@ -3373,7 +3899,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", - "thiserror", + "thiserror 2.0.20", "wasm-encoder", "wasmparser", "wasmtime", @@ -3388,7 +3914,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml_ng", - "thiserror", + "thiserror 2.0.20", "tw-types", ] @@ -3396,7 +3922,7 @@ dependencies = [ name = "tw-secret" version = "0.76.0" dependencies = [ - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -3409,7 +3935,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tracing", "tw-api", @@ -3435,7 +3961,7 @@ dependencies = [ "libc", "notify", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", ] @@ -3445,7 +3971,7 @@ version = "0.76.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", - "thiserror", + "thiserror 2.0.20", "tw-types", ] @@ -3484,12 +4010,52 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unic-langid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05" +dependencies = [ + "unic-langid-impl", +] + +[[package]] +name = "unic-langid-impl" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658" +dependencies = [ + "serde", + "tinystr", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -3825,7 +4391,7 @@ dependencies = [ "pulley-interpreter", "smallvec", "target-lexicon", - "thiserror", + "thiserror 2.0.20", "wasmparser", "wasmtime-environ", "wasmtime-internal-core", @@ -3958,7 +4524,7 @@ dependencies = [ "regalloc2", "smallvec", "target-lexicon", - "thiserror", + "thiserror 2.0.20", "wasmparser", "wasmtime-environ", "wasmtime-internal-core", @@ -4192,6 +4758,18 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "serde", + "zeroize", +] + [[package]] name = "yoke" version = "0.8.3" @@ -4261,6 +4839,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -4279,6 +4871,7 @@ version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", @@ -4295,6 +4888,19 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path", +] + [[package]] name = "zlib-rs" version = "0.6.7" diff --git a/Cargo.toml b/Cargo.toml index 8d4796e5..20beb178 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,9 @@ members = [ # crate、企业版用的第一层都不能沾上,tw-plugin 的 tests/boundary.rs 守着 "crates/tw-plugin", "crates/tw-control", + # 配置包(.twconfig):导出、导入、本机备份与同步共用的格式,以及把一份配置拆成 + # 项目与合并单位的模型 + "crates/tw-pack", # 控制通道的握手与加密。桌面端按 tag 依赖它,所以只依赖契约层和 tw-yaml "crates/tw-link", # ── bin ────────────────────────────────────────────── @@ -76,6 +79,7 @@ tw-dialect = { path = "crates/tw-dialect" } tw-bedrock = { path = "crates/tw-bedrock" } tw-link = { path = "crates/tw-link" } tw-plugin = { path = "crates/tw-plugin" } +tw-pack = { path = "crates/tw-pack" } # ── 版本与企业版 workspace 对齐,便于反向依赖时不打架 ──── tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync", "io-util", "signal"] } @@ -161,6 +165,11 @@ rand = "0.10" zstd = { version = "0.13", default-features = false } clap = { version = "4", features = ["derive"] } +# 配置包的口令加密(scrypt)与同步版本的密钥加密(X25519)。默认特性是空的:不要 +# SSH 密钥、插件、命令行那几样 +age = { version = "0.11", default-features = false } +# 配置包本身是 ZIP。只要 deflate(走已经在依赖树里的 flate2),不要别的压缩算法和加密 +zip = { version = "8", default-features = false, features = ["deflate-flate2"] } # 控制面契约导出成 TypeScript(tw-api 的 `ts` feature)。**不开任何 serde 以外的 # 类型实现**:契约里只有 std 和 serde 的类型 ts-rs = { version = "12", default-features = false, features = ["serde-compat"] } diff --git a/README.md b/README.md index e64940f1..53af4952 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ a time, and cannot stop core, take the diagnostic bundle or change | `tw-observe` | Event bus | | `tw-gateway` | Data plane: the life of a request | | `tw-plugin` | Script-plugin sandbox: QuickJS compiled to WebAssembly, run by Wasmtime | +| `tw-pack` | Configuration packs (`.twconfig`): format, encryption, local backups, and the item model import and sync compare on | | `tw-control` | Control-plane server | ThinkWatch Enterprise depends only on the first four, which depend only on one diff --git a/README.zh-CN.md b/README.zh-CN.md index d07fc7b5..1da1df98 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -93,6 +93,7 @@ twcore control-key --rotate # 更换密钥;用旧密钥建立的连接随 | `tw-observe` | 事件总线 | | `tw-gateway` | 数据面:一个请求的完整生命周期 | | `tw-plugin` | 脚本插件的沙箱:编成 WebAssembly 的 QuickJS,由 Wasmtime 运行 | +| `tw-pack` | 配置包(`.twconfig`):格式、加密、本机备份,以及导入与同步共同比较的项目模型 | | `tw-control` | 控制面服务 | ThinkWatch 企业版只依赖前四个 crate,这四个 crate 也只相互依赖;CI 会针对它们的每一次改动检查企业版能否编译。ThinkWatch Lite 把 `tw-api`、`tw-types`、`tw-yaml`、`tw-guard`、`tw-watch` 和 `tw-link` 固定在某个 Release 的 tag 上,并打包同一 Release 的 `twcore`。接管 AI 客户端和扫描其配置在 Lite 中完成,作用于应用所在的机器;`twcore` 只为每个客户端签发专用的网关密钥。二进制的源码位于 `bin/twcore`。只有 `tw-gateway` 和 `twcore` 可以依赖 `tw-plugin`——它是唯一一个构建时除了 Rust 还需要别的工具的 crate(见下文),因此用这些 crate 构建 Lite 或企业版时都不需要。 diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index a1c07e9c..41d57420 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -492,6 +492,18 @@ l3.not_streamed l3.refused l3.sign_failed l3.stream_failed +pack.bad_entry +pack.corrupt +pack.item_shape +pack.missing_entry +pack.need_key +pack.need_passphrase +pack.schema_too_new +pack.too_large +pack.too_new +pack.verify_failed +pack.wrong_key +pack.wrong_passphrase pricing.sheet.bad_multiplier pricing.sheet.bad_price pricing.sheet.duplicate_name diff --git a/crates/tw-pack/Cargo.toml b/crates/tw-pack/Cargo.toml new file mode 100644 index 00000000..a2a8625c --- /dev/null +++ b/crates/tw-pack/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "tw-pack" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +documentation.workspace = true +readme.workspace = true +description = "Configuration packs (.twconfig): format, encryption, local backups, and the item model that import and sync compare on" + +[dependencies] +# 配置的形状、校验、按名字改一项(保留注释)都在这里 +tw-config = { workspace = true } +tw-engine = { workspace = true } +tw-pricing = { workspace = true } +tw-types = { workspace = true } +tw-yaml = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +serde_yaml_ng = { workspace = true } +thiserror = { workspace = true } +blake3 = { workspace = true } +sha2 = { workspace = true } +age = { workspace = true } +zip = { workspace = true } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/tw-pack/src/lib.rs b/crates/tw-pack/src/lib.rs new file mode 100644 index 00000000..d4cba732 --- /dev/null +++ b/crates/tw-pack/src/lib.rs @@ -0,0 +1,696 @@ +//! 配置包(`.twconfig`):导出、分享、本机备份与同步版本共用的一种文件。 +//! +//! # 文件里有什么 +//! +//! 未加密的配置包是一个 ZIP,里面只许有这几样: +//! +//! ```text +//! manifest.json 格式版本与内容说明([`Manifest`]) +//! config.yaml 配置 +//! plugins/.js 插件脚本 +//! plugins/.approved/.js 批准过的那一份(底稿) +//! client-prefs.json Lite 的通用偏好,Core 不解析 +//! ``` +//! +//! 加密的配置包是 age 格式:口令加密(scrypt),或者加密给一把 X25519 公钥(同步位置的 +//! 版本密钥)。解开之后是同样的 ZIP。两者按文件头区分([`is_encrypted`]),扩展名相同。 +//! +//! # 读的时候不信任文件 +//! +//! 配置包会从别人那里来(分享、导入),所以读的时候按不可信的输入对待:整个文件和解压之后 +//! 的总大小都不超过 [`MAX_BYTES`],ZIP 里出现上面以外的路径(绝对路径、`..`、别的文件名) +//! 整包拒绝,插件 id 必须合规矩,同一个路径出现两次也拒绝。 +//! +//! # 同样的内容,同样的字节 +//! +//! 条目按固定的顺序写、时间戳固定,所以内容相同的两个包只差 `created_at_ms`。比较两个包是 +//! 不是同一份配置用 [`Pack::content_id`]:它只看可以带走的内容(本机设置不算),按 +//! [`model`] 规范化之后再算,注释、排版、默认值写没写都不影响它。 + +use std::collections::BTreeMap; +use std::io::{Read, Write}; + +use serde::{Deserialize, Serialize}; +use tw_types::{Msg, msg}; + +pub mod model; + +/// 配置包格式的版本。**读到更大的就拒绝**([`PackError::TooNew`]):新版本的格式旧版本 +/// 猜不准,猜错了会悄悄丢东西 +pub const FORMAT: u32 = 1; + +/// 一个配置包(连同解压之后的内容)最大多少字节 +pub const MAX_BYTES: usize = 16 * 1024 * 1024; + +/// 扩展名,不带点 +pub const EXTENSION: &str = "twconfig"; + +/// 写进 manifest 的 Core 版本:这几个 crate 的版本,和 `Status.version` 的 CalVer 不是一回事 +pub const CORE_VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// ZIP 里的固定路径 +const MANIFEST: &str = "manifest.json"; +const CONFIG: &str = "config.yaml"; +const PREFS: &str = "client-prefs.json"; +const PLUGINS: &str = "plugins/"; +const APPROVED: &str = "plugins/.approved/"; + +/// ZIP 里最多多少个条目:清单、配置、偏好,加上每个插件两份。再多只会是乱塞的 +const MAX_ENTRIES: usize = 2048; + +/// 一个配置包,解开之后的样子。 +#[derive(Debug, Clone, PartialEq)] +pub struct Pack { + pub manifest: Manifest, + pub config_yaml: String, + /// 插件 id → 文件 + pub plugins: BTreeMap, + /// Lite 的通用偏好。**不解析**:Lite 定义它,Core 只是存着、带着走 + pub client_prefs: Option, +} + +/// 一个插件的两份文件。 +#[derive(Clone, PartialEq, Eq)] +pub struct PluginFiles { + pub script: Vec, + /// 批准过的那一份。和脚本一样(或者没有)就是没有待批准的改动 + pub approved: Option>, +} + +/// 脚本可能有几百 KB,Debug 里只说多长 +impl std::fmt::Debug for PluginFiles { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PluginFiles") + .field("script", &format_args!("{} bytes", self.script.len())) + .field( + "approved", + &self.approved.as_ref().map(|a| format!("{} bytes", a.len())), + ) + .finish() + } +} + +/// `manifest.json`。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Manifest { + pub format: u32, + pub kind: PackKind, + pub created_at_ms: u64, + pub core_version: String, + /// 配置文件格式的版本(`tw_config::SCHEMA_VERSION`) + pub schema: u32, + /// 带没带密钥。不带时上游密钥、请求头的值、AWS 凭据、代理密码、网关密钥都是空的 + pub secrets: bool, + /// **读出来时由文件头决定**,文件里写的不算 + #[serde(default)] + pub encrypted: bool, + pub origin: PackOrigin, + /// 写的时候按内容重算,读的时候也重算:文件里写的只是给人看的 + #[serde(default)] + pub counts: Counts, + /// 同步用的那几项(序号、设备、上一版本、冲突记录),同步那一路自己定义、自己读 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sync: Option, +} + +impl Manifest { + /// 一份新的说明:当前的格式和 Core 版本、此刻的时间、带着密钥、不加密 + pub fn new(kind: PackKind, origin: PackOrigin) -> Self { + Self { + format: FORMAT, + kind, + created_at_ms: now_ms(), + core_version: CORE_VERSION.to_string(), + schema: tw_config::SCHEMA_VERSION, + secrets: true, + encrypted: false, + origin, + counts: Counts::default(), + sync: None, + } + } + + /// 由比这一份 Core 新的版本写的 + pub fn from_newer_core(&self) -> bool { + newer_than_us(&self.core_version) + } +} + +/// 完整的配置,还是选出来的几项(选择项目导出、分享)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PackKind { + Full, + Partial, +} + +/// 这个包是怎么来的。导出和分享之外,和配置的一次改动的来源是同一套词。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PackOrigin { + Export, + Share, + Ui, + Cli, + External, + Defaults, + Sync, + Import, + Restore, + Repair, + /// 更新的版本才有的来源。**读得进来**:一个新词不该让整个包读不了 + #[serde(other)] + Other, +} + +impl PackOrigin { + pub fn slug(&self) -> &'static str { + match self { + PackOrigin::Export => "export", + PackOrigin::Share => "share", + PackOrigin::Ui => "ui", + PackOrigin::Cli => "cli", + PackOrigin::External => "external", + PackOrigin::Defaults => "defaults", + PackOrigin::Sync => "sync", + PackOrigin::Import => "import", + PackOrigin::Restore => "restore", + PackOrigin::Repair => "repair", + PackOrigin::Other => "other", + } + } + + pub fn from_slug(s: &str) -> PackOrigin { + serde_json::from_value(serde_json::Value::String(s.to_string())) + .unwrap_or(PackOrigin::Other) + } +} + +impl From for PackOrigin { + fn from(o: tw_config::history::Origin) -> Self { + use tw_config::history::Origin as O; + match o { + O::Ui => PackOrigin::Ui, + O::Cli => PackOrigin::Cli, + O::External => PackOrigin::External, + O::Defaults => PackOrigin::Defaults, + O::Rollback => PackOrigin::Restore, + // 轮换不留版本,走到这里也只是一个说不出来源的版本 + O::Rotation => PackOrigin::Other, + } + } +} + +/// 包里有多少东西。给列表和预览看。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Counts { + pub providers: u32, + pub proxies: u32, + pub clients: u32, + pub aliases: u32, + pub groups: u32, + pub routes: u32, + pub price_sheets: u32, + pub security_rules: u32, + pub plugins: u32, +} + +impl Counts { + /// 按配置原文数。**读不成 YAML 也不报错**:数不出来就是 0 + pub fn of(config_yaml: &str) -> Counts { + let Ok(doc) = serde_yaml_ng::from_str::(config_yaml) else { + return Counts::default(); + }; + let len = |path: &[&str]| -> u32 { + let mut cur = &doc; + for k in path { + match cur.get(*k) { + Some(v) => cur = v, + None => return 0, + } + } + match cur { + serde_yaml_ng::Value::Sequence(s) => s.len() as u32, + serde_yaml_ng::Value::Mapping(m) => m.len() as u32, + _ => 0, + } + }; + Counts { + providers: len(&["providers"]), + proxies: len(&["proxies"]), + clients: len(&["clients"]), + aliases: len(&["aliases"]), + groups: len(&["groups"]), + routes: len(&["routes"]), + price_sheets: len(&["pricing", "sheets"]), + security_rules: len(&["security", "redact", "custom"]) + + len(&["security", "inspect_tools", "custom"]) + + len(&["security", "content", "custom"]), + plugins: len(&["plugins"]), + } + } +} + +/// 写的时候怎么封。 +pub enum Seal<'a> { + None, + Passphrase(&'a str), + Recipient(&'a age::x25519::Recipient), +} + +/// 读的时候拿什么解。 +pub enum Unseal<'a> { + None, + Passphrase(&'a str), + Identity(&'a age::x25519::Identity), +} + +/// 读写配置包时的失败。**英文只写一遍**:`Display` 就是 [`PackError::msg`] 的原句。 +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PackError { + /// 口令加密的包,没给口令 + #[error("{}", self.msg())] + NeedPassphrase, + #[error("{}", self.msg())] + WrongPassphrase, + /// 加密给一把密钥的包(同步版本),没给密钥 + #[error("{}", self.msg())] + NeedKey, + #[error("{}", self.msg())] + WrongKey, + /// 格式版本比这一份 Core 认得的新 + #[error("{}", self.msg())] + TooNew { format: u32, core_version: String }, + /// 读不成一个配置包:不是 ZIP、ZIP 坏了、清单读不懂、配置不是 UTF-8…… + #[error("{}", self.msg())] + Corrupt { detail: String }, + /// ZIP 里有不该有的路径 + #[error("{}", self.msg())] + BadEntry { name: String }, + /// 少了必须有的那一项(清单、配置) + #[error("{}", self.msg())] + MissingEntry { name: String }, + #[error("{}", self.msg())] + TooLarge { limit: usize }, +} + +impl PackError { + pub fn msg(&self) -> Msg { + match self { + PackError::NeedPassphrase => msg!( + "pack.need_passphrase" => + "This configuration pack is encrypted with a passphrase. Enter the passphrase to open it." + ), + PackError::WrongPassphrase => msg!( + "pack.wrong_passphrase" => + "The passphrase is not correct." + ), + PackError::NeedKey => msg!( + "pack.need_key" => + "This configuration pack is encrypted for a sync location and cannot be opened with a passphrase." + ), + PackError::WrongKey => msg!( + "pack.wrong_key" => + "This configuration pack is encrypted with a different key." + ), + PackError::TooNew { + format, + core_version, + } => msg!( + "pack.too_new", format = format, version = core_version => + "This configuration pack was exported by a newer version (Core {version}, format \ + {format}). Update ThinkWatch Lite first." + ), + PackError::Corrupt { detail } => msg!( + "pack.corrupt", detail = detail => + "This file is not a readable configuration pack: {detail}" + ), + PackError::BadEntry { name } => msg!( + "pack.bad_entry", name = name => + "This configuration pack contains `{name}`, which a configuration pack may not \ + contain, so it was not opened." + ), + PackError::MissingEntry { name } => msg!( + "pack.missing_entry", name = name => + "This configuration pack has no {name}." + ), + PackError::TooLarge { limit } => msg!( + "pack.too_large", limit = limit / (1024 * 1024) => + "This configuration pack is larger than {limit} MiB." + ), + } + } +} + +fn corrupt(detail: impl std::fmt::Display) -> PackError { + PackError::Corrupt { + detail: detail.to_string(), + } +} + +// ─────────────────────────────────────────────────────────── 写 + +/// 把一个包写成文件的字节。`counts` 和 `encrypted` 按内容重算,别的照 `pack.manifest`。 +pub fn write(pack: &Pack, seal: Seal) -> Result, PackError> { + let mut manifest = pack.manifest.clone(); + manifest.counts = Counts::of(&pack.config_yaml); + manifest.encrypted = !matches!(seal, Seal::None); + let plain = zip_bytes(pack, &manifest)?; + if plain.len() > MAX_BYTES { + return Err(PackError::TooLarge { limit: MAX_BYTES }); + } + let out = match seal { + Seal::None => plain, + Seal::Passphrase(p) => { + let mut r = + age::scrypt::Recipient::new(age::secrecy::SecretString::from(p.to_string())); + r.set_work_factor(work_factor()); + encrypt(&plain, &r)? + } + Seal::Recipient(r) => encrypt(&plain, r)?, + }; + if out.len() > MAX_BYTES { + return Err(PackError::TooLarge { limit: MAX_BYTES }); + } + Ok(out) +} + +fn zip_bytes(pack: &Pack, manifest: &Manifest) -> Result, PackError> { + // **解压之后的总量也不超过上限**:读的时候按它挡,写出去的就得读得回来 + let unpacked = pack.config_yaml.len() + + pack + .plugins + .values() + .map(|f| f.script.len() + f.approved.as_ref().map_or(0, Vec::len)) + .sum::() + + pack + .client_prefs + .as_ref() + .map_or(0, |p| p.to_string().len() * 2); + if unpacked > MAX_BYTES { + return Err(PackError::TooLarge { limit: MAX_BYTES }); + } + let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + // **时间戳固定**:同样的内容写出同样的字节 + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated) + .last_modified_time(zip::DateTime::DEFAULT) + .unix_permissions(0o600); + let mut put = |name: &str, bytes: &[u8]| -> Result<(), PackError> { + z.start_file(name, opts).map_err(corrupt)?; + z.write_all(bytes).map_err(corrupt) + }; + let manifest_json = serde_json::to_vec_pretty(manifest).map_err(corrupt)?; + put(MANIFEST, &manifest_json)?; + put(CONFIG, pack.config_yaml.as_bytes())?; + if let Some(p) = &pack.client_prefs { + put(PREFS, &serde_json::to_vec_pretty(p).map_err(corrupt)?)?; + } + for (id, files) in &pack.plugins { + if !tw_config::plugins::valid_id(id) { + return Err(PackError::BadEntry { + name: format!("{PLUGINS}{id}.js"), + }); + } + put(&format!("{PLUGINS}{id}.js"), &files.script)?; + if let Some(a) = &files.approved { + put(&format!("{APPROVED}{id}.js"), a)?; + } + } + Ok(z.finish().map_err(corrupt)?.into_inner()) +} + +fn encrypt(plain: &[u8], r: &dyn age::Recipient) -> Result, PackError> { + let e = age::Encryptor::with_recipients(std::iter::once(r)).map_err(corrupt)?; + let mut out = Vec::with_capacity(plain.len() + 256); + let mut w = e.wrap_output(&mut out).map_err(corrupt)?; + w.write_all(plain).map_err(corrupt)?; + w.finish().map_err(corrupt)?; + Ok(out) +} + +/// scrypt 的工作量(`N = 2^log_n`)。**固定,不按这台机器的快慢挑**:同步位置上的版本由 +/// 哪台设备写、哪台设备读都不一定,快的那台挑出来的工作量慢的那台可能解不开。18 是 age +/// 自己的下限,一台普通的电脑一秒以内 +fn work_factor() -> u8 { + match TEST_WORK_FACTOR.load(std::sync::atomic::Ordering::Relaxed) { + 0 => 18, + n => n, + } +} + +/// 解开时最多接受多大的工作量。比写的时候大一些:将来调高了,旧版本照样读得了新包 +const MAX_WORK_FACTOR: u8 = 22; + +/// **只给测试用**:把口令加密的工作量调低,测试不用每次等一秒。0 是不改 +#[doc(hidden)] +pub static TEST_WORK_FACTOR: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +// ─────────────────────────────────────────────────────────── 读 + +/// 这些字节是不是加密的配置包(age 的二进制格式)。 +pub fn is_encrypted(bytes: &[u8]) -> bool { + bytes.starts_with(b"age-encryption.org/") +} + +/// 读一个配置包。 +pub fn read(bytes: &[u8], unseal: Unseal) -> Result { + if bytes.len() > MAX_BYTES { + return Err(PackError::TooLarge { limit: MAX_BYTES }); + } + let encrypted = is_encrypted(bytes); + let plain; + let zip_bytes: &[u8] = if encrypted { + plain = decrypt(bytes, unseal)?; + &plain + } else { + bytes + }; + let mut pack = unzip(zip_bytes)?; + pack.manifest.encrypted = encrypted; + pack.manifest.counts = Counts::of(&pack.config_yaml); + Ok(pack) +} + +fn decrypt(bytes: &[u8], unseal: Unseal) -> Result, PackError> { + let d = age::Decryptor::new_buffered(bytes).map_err(|e| match e { + age::DecryptError::UnknownFormat => PackError::TooNew { + format: FORMAT + 1, + core_version: String::new(), + }, + other => corrupt(other), + })?; + let reader = if d.is_scrypt() { + let Unseal::Passphrase(p) = unseal else { + return Err(PackError::NeedPassphrase); + }; + let mut id = age::scrypt::Identity::new(age::secrecy::SecretString::from(p.to_string())); + id.set_max_work_factor(MAX_WORK_FACTOR); + d.decrypt(std::iter::once(&id as &dyn age::Identity)) + .map_err(|e| match e { + age::DecryptError::DecryptionFailed | age::DecryptError::NoMatchingKeys => { + PackError::WrongPassphrase + } + other => corrupt(other), + })? + } else { + let Unseal::Identity(id) = unseal else { + return Err(PackError::NeedKey); + }; + d.decrypt(std::iter::once(id as &dyn age::Identity)) + .map_err(|e| match e { + age::DecryptError::NoMatchingKeys | age::DecryptError::DecryptionFailed => { + PackError::WrongKey + } + other => corrupt(other), + })? + }; + let mut out = Vec::new(); + reader + .take(MAX_BYTES as u64 + 1) + .read_to_end(&mut out) + .map_err(corrupt)?; + if out.len() > MAX_BYTES { + return Err(PackError::TooLarge { limit: MAX_BYTES }); + } + Ok(out) +} + +/// ZIP 里的一个路径是什么。 +enum Entry { + Manifest, + Config, + Prefs, + Script(String), + Approved(String), + /// `plugins/`、`plugins/.approved/` 这两个目录条目:别的工具打包时会带上,无害 + Dir, +} + +fn entry_of(name: &str) -> Option { + let plugin = |rest: &str| { + let id = rest.strip_suffix(".js")?; + tw_config::plugins::valid_id(id).then(|| id.to_string()) + }; + match name { + MANIFEST => Some(Entry::Manifest), + CONFIG => Some(Entry::Config), + PREFS => Some(Entry::Prefs), + PLUGINS | APPROVED => Some(Entry::Dir), + _ => { + if let Some(rest) = name.strip_prefix(APPROVED) { + plugin(rest).map(Entry::Approved) + } else if let Some(rest) = name.strip_prefix(PLUGINS) { + plugin(rest).map(Entry::Script) + } else { + None + } + } + } +} + +fn unzip(bytes: &[u8]) -> Result { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(corrupt)?; + if z.len() > MAX_ENTRIES { + return Err(corrupt(format!("it has {} entries", z.len()))); + } + let mut manifest: Option = None; + let mut config: Option = None; + let mut prefs: Option = None; + let mut scripts: BTreeMap> = BTreeMap::new(); + let mut approved: BTreeMap> = BTreeMap::new(); + let mut seen = std::collections::BTreeSet::new(); + // 解压出来的总量。**按真读到的算**:条目头里写的大小可以是假的 + let mut budget = MAX_BYTES; + for i in 0..z.len() { + let mut f = z.by_index(i).map_err(corrupt)?; + let name = f.name().to_string(); + let Some(kind) = entry_of(&name) else { + return Err(PackError::BadEntry { name }); + }; + if !seen.insert(name.clone()) { + return Err(PackError::BadEntry { name }); + } + if matches!(kind, Entry::Dir) { + continue; + } + if f.is_dir() { + return Err(PackError::BadEntry { name }); + } + let mut buf = Vec::new(); + (&mut f) + .take(budget as u64 + 1) + .read_to_end(&mut buf) + .map_err(corrupt)?; + if buf.len() > budget { + return Err(PackError::TooLarge { limit: MAX_BYTES }); + } + budget -= buf.len(); + match kind { + Entry::Manifest => { + // 先按最宽的读出格式版本:更新的格式整份读不懂时,要说的是「太新」 + let raw: serde_json::Value = serde_json::from_slice(&buf) + .map_err(|e| corrupt(format!("{MANIFEST}: {e}")))?; + let format = raw.get("format").and_then(serde_json::Value::as_u64); + if let Some(f) = format + && f > u64::from(FORMAT) + { + return Err(PackError::TooNew { + format: f as u32, + core_version: raw + .get("core_version") + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .to_string(), + }); + } + manifest = Some( + serde_json::from_value(raw).map_err(|e| corrupt(format!("{MANIFEST}: {e}")))?, + ); + } + Entry::Config => { + config = Some( + String::from_utf8(buf) + .map_err(|_| corrupt(format!("{CONFIG} is not UTF-8")))?, + ); + } + Entry::Prefs => { + prefs = Some( + serde_json::from_slice(&buf).map_err(|e| corrupt(format!("{PREFS}: {e}")))?, + ); + } + Entry::Script(id) => { + scripts.insert(id, buf); + } + Entry::Approved(id) => { + approved.insert(id, buf); + } + Entry::Dir => {} + } + } + let manifest = manifest.ok_or_else(|| PackError::MissingEntry { + name: MANIFEST.to_string(), + })?; + let config_yaml = config.ok_or_else(|| PackError::MissingEntry { + name: CONFIG.to_string(), + })?; + // 只有底稿、没有脚本的不是一个插件 + if let Some(id) = approved.keys().find(|id| !scripts.contains_key(*id)) { + return Err(PackError::BadEntry { + name: format!("{APPROVED}{id}.js"), + }); + } + let plugins = scripts + .into_iter() + .map(|(id, script)| { + let approved = approved.remove(&id); + (id, PluginFiles { script, approved }) + }) + .collect(); + Ok(Pack { + manifest, + config_yaml, + plugins, + client_prefs: prefs, + }) +} + +// ─────────────────────────────────────────────────────────── 杂项 + +impl Pack { + /// 这份内容的标识:可以带走的内容([`model::snapshot`])规范化之后的 blake3,前 12 位 + /// 十六进制。**本机设置不算**,所以本机备份和它上传到同步位置的那一版对得上;注释、 + /// 排版、默认值写没写都不影响它。读不成配置时按原文算 + pub fn content_id(&self) -> String { + model::content_id(self) + } +} + +pub(crate) fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// `0.77.0` 这样的版本号,比这一份 Core 新吗。读不懂的不算新 +pub fn newer_than_us(version: &str) -> bool { + match (parse_version(version), parse_version(CORE_VERSION)) { + (Some(theirs), Some(ours)) => theirs > ours, + _ => false, + } +} + +fn parse_version(v: &str) -> Option<(u64, u64, u64)> { + let core = v.trim().split(['-', '+']).next()?; + let mut it = core.split('.').map(|p| p.parse::().ok()); + Some(( + it.next()??, + it.next().flatten().unwrap_or(0), + it.next().flatten().unwrap_or(0), + )) +} + +#[cfg(test)] +mod tests; diff --git a/crates/tw-pack/src/model/codec.rs b/crates/tw-pack/src/model/codec.rs new file mode 100644 index 00000000..e354a9a1 --- /dev/null +++ b/crates/tw-pack/src/model/codec.rs @@ -0,0 +1,47 @@ +//! 插件源码怎么拆成「代码」和「数据」。 +//! +//! 插件的设置写在它自己的文件里(manifest 字面量里的出错时怎么办、范围、设置的值)。比较 +//! 时这两样分开:一台设备改了设置、另一台改了代码,各改各的,不算冲突。读 manifest 要 +//! 插件运行时那一套(编它要一个能出 wasm 的 clang),这个 crate 不依赖它:Core 启动时把 +//! 真的拆法装进来([`super::install_codec`]),没装时整份文件当代码([`WholeFile`])。 + +use serde_json::Value as Json; + +/// 插件源码的拆法。 +pub trait PluginCodec: Send + Sync { + /// 拆成两份:**代码**是数据换成缺省之后的完整源码(manifest 那一段按固定的样子重写, + /// 只差数据的两份源码拆出来的代码一字不差),**数据**是出错时怎么办、范围和设置的值。 + /// 读不出 manifest 的是 None:整份当代码 + fn split(&self, source: &str) -> Option<(String, Json)>; + + /// 把数据写进源码,别的字节不动。写不进去(数据和源码声明的对不上)是 None + fn join(&self, source: &str, data: &Json) -> Option; + + /// 随这一份 Core 发的默认插件的源码。不是默认插件是 None + fn shipped(&self, id: &str) -> Option; + + /// 改得了回答里的工具调用(权限有 `reply_tool_calls`):这种插件每台设备分别批准, + /// 别处来的版本落到本机时先不批准。读不出来的按要批准算 + fn needs_approval(&self, source: &str) -> bool; +} + +/// 不拆:整份文件是代码,没有数据,没有默认插件,一律要批准。 +pub struct WholeFile; + +impl PluginCodec for WholeFile { + fn split(&self, _source: &str) -> Option<(String, Json)> { + None + } + + fn join(&self, source: &str, data: &Json) -> Option { + data.is_null().then(|| source.to_string()) + } + + fn shipped(&self, _id: &str) -> Option { + None + } + + fn needs_approval(&self, _source: &str) -> bool { + true + } +} diff --git a/crates/tw-pack/src/model/items.rs b/crates/tw-pack/src/model/items.rs new file mode 100644 index 00000000..08615a64 --- /dev/null +++ b/crates/tw-pack/src/model/items.rs @@ -0,0 +1,728 @@ +//! 配置 → 项目,项目 → 配置里的一项,以及项目之间的引用。 + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Map, Value as Json}; +use serde_yaml_ng::{Mapping, Value as Yaml}; +use tw_config::{Config, Protocol, Provider}; + +use super::json::{key, to_json, to_yaml, typed_mapping}; +use super::{GUARDS, Item, ItemId, ItemKind, ModelError, PluginCodec, global, unit}; +use crate::{Pack, PluginFiles}; + +/// ChatGPT 账号登录所得的账户 ID 所在的请求头:跟着登录走,不随配置带走 +pub(crate) const ACCOUNT_HEADER: &str = tw_config::chatgpt::ACCOUNT_HEADER; + +/// 一个上游是 ChatGPT 账号。它的登录(`oauth`)和账户 ID 请求头属于这台设备 +pub(crate) fn is_chatgpt(p: &Provider) -> bool { + p.effective_protocol() == Some(Protocol::Chatgpt) +} + +fn shape(item: &ItemId, detail: impl std::fmt::Display) -> ModelError { + ModelError::Shape { + item: item.to_string(), + detail: detail.to_string(), + } +} + +// ─────────────────────────────────────────────────────────── 配置 → 项目 + +pub(crate) fn of_config( + cfg: &Config, + pack: &Pack, + codec: &dyn PluginCodec, +) -> Result, ModelError> { + let mut out = BTreeMap::new(); + let mut put = |id: ItemId, units: BTreeMap| { + out.insert( + id, + Item { + units, + ..Default::default() + }, + ); + }; + + for p in &cfg.providers { + let id = ItemId::new(ItemKind::Provider, &p.name); + let units = provider_units(p).map_err(|e| shape(&id, e))?; + put(id, units); + } + order( + &mut put, + ItemKind::ProviderOrder, + cfg.providers.iter().map(|p| &p.name), + ); + + for px in &cfg.proxies { + let id = ItemId::new(ItemKind::Proxy, &px.name); + let units = whole(px, "name").map_err(|e| shape(&id, e))?; + put(id, units); + } + for c in &cfg.clients { + let id = ItemId::new(ItemKind::Key, &c.name); + let units = whole(c, "name").map_err(|e| shape(&id, e))?; + put(id, units); + } + for a in cfg.aliases.iter() { + let id = ItemId::new(ItemKind::Alias, &a.name); + put( + id, + one(Json::Array( + a.models.iter().cloned().map(Json::String).collect(), + )), + ); + } + for g in &cfg.groups { + let id = ItemId::new(ItemKind::Group, &g.name); + let units = whole(g, "name").map_err(|e| shape(&id, e))?; + put(id, units); + } + for r in &cfg.routes { + let id = ItemId::new(ItemKind::Route, &r.name); + let units = whole(r, "name").map_err(|e| shape(&id, e))?; + put(id, units); + } + order( + &mut put, + ItemKind::RouteOrder, + cfg.routes.iter().map(|r| &r.name), + ); + for s in &cfg.pricing.sheets { + let id = ItemId::new(ItemKind::PriceSheet, &s.name); + let units = whole(s, "name").map_err(|e| shape(&id, e))?; + put(id, units); + } + let rules: [(&str, Vec); 3] = [ + ("redact", rule_values(&cfg.security.redact.custom)), + ( + "inspect_tools", + rule_values(&cfg.security.inspect_tools.custom), + ), + ("content", rule_values(&cfg.security.content.custom)), + ]; + for (guard, list) in rules { + for v in list { + let Json::Object(mut o) = v else { continue }; + let name = o + .remove("name") + .and_then(|n| n.as_str().map(str::to_string)) + .unwrap_or_default(); + put( + ItemId::new(ItemKind::SecurityRule, format!("{guard}/{name}")), + one(Json::Object(o)), + ); + } + } + + for p in &cfg.plugins { + let id = ItemId::new(ItemKind::Plugin, &p.id); + let files = pack.plugins.get(&p.id); + let (units, files) = plugin_units(p, files, codec); + out.insert( + id, + Item { + units, + files, + ..Default::default() + }, + ); + } + let mut put = |id: ItemId, units: BTreeMap| { + out.insert( + id, + Item { + units, + ..Default::default() + }, + ); + }; + order( + &mut put, + ItemKind::PluginOrder, + cfg.plugins.iter().map(|p| &p.id), + ); + + for (name, units) in + global_units(cfg).map_err(|e| shape(&ItemId::new(ItemKind::Global, ""), e))? + { + if !units.is_empty() { + put(ItemId::new(ItemKind::Global, name), units); + } + } + + if let Some(prefs) = &pack.client_prefs { + let mut units = BTreeMap::new(); + super::json::flatten("", prefs, &mut units); + if !units.is_empty() && prefs != &Json::Object(Default::default()) { + put(ItemId::new(ItemKind::ClientPrefs, ""), units); + } + } + Ok(out) +} + +fn one(v: Json) -> BTreeMap { + BTreeMap::from([(unit::ALL.to_string(), v)]) +} + +fn order<'a>( + put: &mut impl FnMut(ItemId, BTreeMap), + kind: ItemKind, + names: impl Iterator, +) { + let list: Vec = names.cloned().map(Json::String).collect(); + if !list.is_empty() { + put(ItemId::new(kind, ""), one(Json::Array(list))); + } +} + +/// 整个对象是一个单位,名字不在里面(名字是项目的标识) +fn whole(v: &T, name_key: &str) -> Result, String> { + match to_json(v)? { + Json::Object(mut o) => { + o.remove(name_key); + Ok(one(Json::Object(o))) + } + _ => Err("it does not serialize to an object".into()), + } +} + +fn rule_values(rules: &[T]) -> Vec { + rules.iter().filter_map(|r| to_json(r).ok()).collect() +} + +// ─────────────────────────────────────────────────────────── 上游 + +/// 上游的一个字段归哪个单位。**不认识的归 `other`**:将来新加的字段照样参与比较 +fn provider_unit(field: &str) -> &'static str { + match field { + "base_url" | "protocol" | "key" | "headers" | "oauth" | "aws" | "proxy" + | "on_proxy_fail" | "signed_in" => unit::CONN, + "models" | "models_only" | "model_specs" => unit::MODELS, + "billing" | "pricing" => unit::BILLING, + _ => unit::OTHER, + } +} + +pub(crate) const PROVIDER_UNITS: &[&str] = &[unit::CONN, unit::MODELS, unit::BILLING, unit::OTHER]; + +/// 去掉这台设备自己的部分:ChatGPT 的登录和账户 ID 请求头 +pub(crate) fn shareable(p: &Provider) -> Provider { + let mut p = p.clone(); + if is_chatgpt(&p) { + p.oauth = None; + p.headers = tw_config::Headers::new( + p.headers + .iter() + .filter(|h| !h.name.eq_ignore_ascii_case(ACCOUNT_HEADER)) + .cloned() + .collect(), + ); + } + p +} + +fn provider_units(p: &Provider) -> Result, String> { + let p = shareable(p); + let Json::Object(mut obj) = to_json(&p)? else { + return Err("it does not serialize to an object".into()); + }; + obj.remove("name"); + // **请求头按写的顺序**:JSON 对象的键是排过序的,所以写成一串 [名字, 值] + if obj.contains_key("headers") { + obj.insert( + "headers".into(), + Json::Array( + p.headers + .iter() + .map(|h| { + Json::Array(vec![ + Json::String(h.name.clone()), + Json::String(h.value.raw().to_string()), + ]) + }) + .collect(), + ), + ); + } + let mut units: BTreeMap> = PROVIDER_UNITS + .iter() + .map(|u| (u.to_string(), Map::new())) + .collect(); + for (k, v) in obj { + units + .get_mut(provider_unit(&k)) + .expect("every unit is there") + .insert(k, v); + } + Ok(units + .into_iter() + .map(|(k, v)| (k, Json::Object(v))) + .collect()) +} + +/// 上游的单位拼回配置里的那一项。`local` 是本机同名的那一家:它是 ChatGPT 账号、拼出来 +/// 的也是的话,登录和账户 ID 请求头取它的 +pub(crate) fn provider_mapping( + id: &ItemId, + units: &BTreeMap, + local: Option<&Provider>, +) -> Result<(Provider, Mapping), ModelError> { + let mut m = Mapping::new(); + m.insert(key("name"), Yaml::String(id.name.clone())); + for (u, v) in units { + let Json::Object(o) = v else { + return Err(shape(id, format!("unit `{u}` is not an object"))); + }; + for (k, v) in o { + let value = if k == "headers" { + headers_yaml(v).map_err(|e| shape(id, e))? + } else { + to_yaml(v) + }; + m.insert(key(k), value); + } + } + let (mut p, _) = typed_mapping::(Yaml::Mapping(m)).map_err(|e| shape(id, e))?; + if let Some(local) = local + && is_chatgpt(&p) + && is_chatgpt(local) + { + p.oauth = local.oauth.clone(); + if let Some(h) = local.headers.get(ACCOUNT_HEADER) { + let mut all: Vec = p + .headers + .iter() + .filter(|x| !x.name.eq_ignore_ascii_case(ACCOUNT_HEADER)) + .cloned() + .collect(); + all.push(h.clone()); + p.headers = tw_config::Headers::new(all); + } + } + let m = match serde_yaml_ng::to_value(&p) { + Ok(Yaml::Mapping(m)) => m, + _ => return Err(shape(id, "it does not serialize to a mapping")), + }; + Ok((p, m)) +} + +/// `[[名字, 值], …]` → 按这个顺序的 YAML 映射 +fn headers_yaml(v: &Json) -> Result { + let Json::Array(pairs) = v else { + return Err("headers is not a list of pairs".into()); + }; + let mut m = Mapping::new(); + for p in pairs { + match p.as_array().map(Vec::as_slice) { + Some([Json::String(n), Json::String(v)]) => { + m.insert(key(n), Yaml::String(v.clone())); + } + _ => return Err("headers is not a list of pairs".into()), + } + } + Ok(Yaml::Mapping(m)) +} + +// ─────────────────────────────────────────────────────────── 别的有名字的 + +/// 一个只有 `all` 的项目拼回配置里的那一项(名字键叫 `name_key`),按类型 `T` 核过、 +/// 写成它的字段顺序 +pub(crate) fn whole_mapping( + id: &ItemId, + name: &str, + units: &BTreeMap, +) -> Result<(T, Mapping), ModelError> +where + T: serde::de::DeserializeOwned + serde::Serialize, +{ + let mut m = Mapping::new(); + m.insert(key("name"), Yaml::String(name.to_string())); + match units.get(unit::ALL) { + Some(Json::Object(o)) => { + for (k, v) in o { + m.insert(key(k), to_yaml(v)); + } + } + Some(_) => return Err(shape(id, "unit `all` is not an object")), + None => return Err(shape(id, "unit `all` is missing")), + } + typed_mapping::(Yaml::Mapping(m)).map_err(|e| shape(id, e)) +} + +/// 别名的模型列表 +pub(crate) fn alias_models( + id: &ItemId, + units: &BTreeMap, +) -> Result, ModelError> { + match units.get(unit::ALL) { + Some(Json::Array(a)) => a + .iter() + .map(|m| { + m.as_str() + .map(str::to_string) + .ok_or_else(|| shape(id, "a model is not a string")) + }) + .collect(), + _ => Err(shape(id, "unit `all` is not a list of models")), + } +} + +/// 顺序项目里的名字 +pub(crate) fn order_names(units: &BTreeMap) -> Vec { + match units.get(unit::ALL) { + Some(Json::Array(a)) => a + .iter() + .filter_map(|n| n.as_str().map(str::to_string)) + .collect(), + _ => Vec::new(), + } +} + +// ─────────────────────────────────────────────────────────── 插件 + +/// 一个插件的单位,和带着走的文件。 +/// +/// **比较的是批准过的那一份**:文件被人改了、还没批准时,脚本那个单位按底稿算 —— 没批准的 +/// 改动不该借导出或同步跑到别的设备上,在那里被当成批准过的。底稿和配置里的哈希都对不上时 +/// 按文件算(导入时这样的插件是错误) +fn plugin_units( + entry: &tw_config::Plugin, + files: Option<&PluginFiles>, + codec: &dyn PluginCodec, +) -> (BTreeMap, Option) { + let mut units = BTreeMap::new(); + units.insert(unit::ENABLED.to_string(), Json::Bool(entry.enabled)); + let Some(files) = files else { + return (units, None); + }; + let source = approved_source(entry, files); + let text = String::from_utf8_lossy(source).into_owned(); + let (code, data) = match codec.split(&text) { + Some((code, data)) => (code, Some(data)), + None => (text, None), + }; + let shipped = codec + .shipped(&entry.id) + .map(|s| codec.split(&s).map_or(s, |(c, _)| c)); + // 随 Core 发的默认插件、代码没动过:脚本由各设备自己的 Core 给,不比较 + if shipped.as_deref() != Some(code.as_str()) { + units.insert(unit::SCRIPT.to_string(), Json::String(code)); + } + if let Some(d) = data { + units.insert(unit::SETTINGS.to_string(), d); + } + (units, Some(files.clone())) +} + +/// 批准过的那一份:哈希对得上配置的脚本或底稿。都对不上是脚本 +pub(crate) fn approved_source<'a>(entry: &tw_config::Plugin, files: &'a PluginFiles) -> &'a [u8] { + if sha256_hex(&files.script) == entry.sha256 { + return &files.script; + } + match &files.approved { + Some(a) if sha256_hex(a) == entry.sha256 => a, + _ => &files.script, + } +} + +pub(crate) fn sha256_hex(bytes: &[u8]) -> String { + use sha2::Digest; + let d = sha2::Sha256::digest(bytes); + d.iter().map(|b| format!("{b:02x}")).collect() +} + +// ─────────────────────────────────────────────────────────── 全局设置 + +/// 每一节的单位:等于默认值的字段不在里面 +/// 一节全局设置的单位 +type Units = BTreeMap; + +fn global_units(cfg: &Config) -> Result, String> { + let mut out = Vec::new(); + out.push(( + global::FAILOVER, + fields(global::FAILOVER, &to_json(&cfg.failover)?), + )); + let mut sec = BTreeMap::new(); + if let Json::Object(o) = to_json(&cfg.security)? { + for (guard, v) in o { + let Json::Object(fields) = v else { continue }; + for (f, v) in fields { + if f == "custom" { + continue; + } + match (f.as_str(), v) { + ("actions", Json::Object(actions)) => { + for (rule, a) in actions { + sec.insert(format!("{}.{guard}.actions.{rule}", global::SECURITY), a); + } + } + (_, v) => { + sec.insert(format!("{}.{guard}.{f}", global::SECURITY), v); + } + } + } + } + } + out.push((global::SECURITY, sec)); + let scalar = |name: &str, v: Option<&String>| -> BTreeMap { + v.map(|v| BTreeMap::from([(name.to_string(), Json::String(v.clone()))])) + .unwrap_or_default() + }; + out.push(( + global::DEFAULT_ROUTE, + scalar(global::DEFAULT_ROUTE, cfg.default_route.as_ref()), + )); + out.push(( + global::DEFAULT_KEY, + scalar(global::DEFAULT_KEY, cfg.default_key.as_ref()), + )); + out.push(( + global::CLIENT_PROBES, + fields(global::CLIENT_PROBES, &to_json(&cfg.client_probes)?), + )); + let mut pricing = to_json(&cfg.pricing)?; + if let Json::Object(o) = &mut pricing { + o.remove("sheets"); + } + out.push((global::PRICING, fields(global::PRICING, &pricing))); + for (_, units) in out.iter_mut() { + units.retain(|path, v| !is_global_default(path, v)); + } + Ok(out) +} + +fn fields(section: &str, v: &Json) -> BTreeMap { + match v { + Json::Object(o) => o + .iter() + .map(|(k, v)| (format!("{section}.{k}"), v.clone())) + .collect(), + _ => BTreeMap::new(), + } +} + +/// 全局设置的一个单位按路径拆开:节名,和节里的那几步 +pub(crate) fn global_path(path: &str) -> Vec { + let limit = if path.starts_with("security.") { 4 } else { 2 }; + path.splitn(limit, '.').map(str::to_string).collect() +} + +/// 一节的默认值写成 JSON,和读进它的类型。节名不认识是 None +fn section_default(section: &str) -> Option { + match section { + global::FAILOVER => to_json(&tw_config::Failover::default()).ok(), + global::SECURITY => to_json(&tw_config::Security::default()).ok(), + global::CLIENT_PROBES => to_json(&tw_config::ClientProbes::default()).ok(), + global::PRICING => to_json(&tw_pricing_default()).ok(), + _ => None, + } +} + +fn tw_pricing_default() -> Json { + let mut d = to_json(&tw_pricing::PricingConfig::default()).unwrap_or(Json::Null); + if let Json::Object(o) = &mut d { + o.remove("sheets"); + } + d +} + +/// 一节的 JSON 读进它的类型,再写出来:默认值去掉。读不进去是 Err +pub(crate) fn section_normalized(section: &str, v: &Json) -> Result { + fn round(v: &Json) -> Result { + let t: T = serde_json::from_value(v.clone()).map_err(|e| e.to_string())?; + to_json(&t) + } + match section { + global::FAILOVER => round::(v), + global::SECURITY => round::(v), + global::CLIENT_PROBES => round::(v), + global::PRICING => { + let mut out = round::(v)?; + if let Json::Object(o) = &mut out { + o.remove("sheets"); + } + Ok(out) + } + other => Err(format!("there is no section `{other}`")), + } +} + +/// 全局设置的一个单位是不是等于默认值。**按类型判断**:把它写进默认的那一节、读进类型 +/// 再写出来,和默认的那一节一样就是默认值 —— 序列化时省掉的默认值也认得出 +pub(crate) fn is_global_default(path: &str, v: &Json) -> bool { + let parts = global_path(path); + match parts.as_slice() { + [s] if s == global::DEFAULT_ROUTE => v.as_str() == Some(tw_engine::DEFAULT_ROUTE), + [s] if s == global::DEFAULT_KEY => v.as_str() == Some(tw_config::DEFAULT_KEY), + [section, rest @ ..] if !rest.is_empty() => { + let Some(default) = section_default(section) else { + return false; + }; + let mut with = default.clone(); + set_path(&mut with, rest, v.clone()); + match section_normalized(section, &with) { + Ok(n) => n == default, + Err(_) => false, + } + } + _ => false, + } +} + +/// 在一棵 JSON 里按路径写一个值,缺的对象补出来 +pub(crate) fn set_path(root: &mut Json, path: &[String], v: Json) { + let mut cur = root; + for (i, p) in path.iter().enumerate() { + if !cur.is_object() { + *cur = Json::Object(Default::default()); + } + let o = cur.as_object_mut().expect("just made it an object"); + if i + 1 == path.len() { + o.insert(p.clone(), v); + return; + } + cur = o + .entry(p.clone()) + .or_insert_with(|| Json::Object(Default::default())); + } +} + +// ─────────────────────────────────────────────────────────── 引用 + +pub(crate) fn relink(items: &mut BTreeMap) { + let names = |kind: ItemKind| -> BTreeSet { + items + .keys() + .filter(|id| id.kind == kind) + .map(|id| id.name.clone()) + .collect() + }; + let groups = names(ItemKind::Group); + let aliases = names(ItemKind::Alias); + for (id, item) in items.iter_mut() { + item.refs = refs_of(id, &item.units, &groups, &aliases); + } +} + +fn refs_of( + id: &ItemId, + units: &BTreeMap, + groups: &BTreeSet, + aliases: &BTreeSet, +) -> BTreeSet { + let mut out = BTreeSet::new(); + let s = |v: Option<&Json>| v.and_then(Json::as_str).map(str::to_string); + let all = units.get(unit::ALL); + let get = |v: Option<&Json>, k: &str| v.and_then(|v| v.get(k)).cloned(); + match id.kind { + ItemKind::Provider => { + if let Some(px) = s(units.get(unit::CONN).and_then(|c| c.get("proxy"))) + && px != tw_config::DIRECT + && px != tw_config::SYSTEM + { + out.insert(ItemId::new(ItemKind::Proxy, px)); + } + if let Some(sheet) = s(units.get(unit::BILLING).and_then(|c| c.get("pricing"))) { + out.insert(ItemId::new(ItemKind::PriceSheet, sheet)); + } + } + ItemKind::Key => { + if let Some(r) = s(get(all, "route").as_ref()) { + out.insert(ItemId::new(ItemKind::Route, r)); + } + for m in get(all, "allow") + .and_then(|a| a.as_array().cloned()) + .unwrap_or_default() + { + if let Some(m) = m.as_str() + && aliases.contains(m) + { + out.insert(ItemId::new(ItemKind::Alias, m)); + } + } + } + ItemKind::Group => { + for m in get(all, "providers") + .and_then(|a| a.as_array().cloned()) + .unwrap_or_default() + { + let name = m.as_str().map(str::to_string).or_else(|| s(m.get("name"))); + if let Some(n) = name { + out.insert(ItemId::new(ItemKind::Provider, n)); + } + } + if let Some(sel) = s(get(all, "selected").as_ref()) { + out.insert(ItemId::new(ItemKind::Provider, sel)); + } + } + ItemKind::Route => { + for rule in get(all, "rules") + .and_then(|a| a.as_array().cloned()) + .unwrap_or_default() + { + match rule.get("to") { + Some(Json::String(n)) if n == tw_engine::ALL_UPSTREAMS => {} + Some(Json::String(n)) if groups.contains(n) => { + out.insert(ItemId::new(ItemKind::Group, n)); + } + Some(Json::String(n)) => { + out.insert(ItemId::new(ItemKind::Provider, n)); + } + Some(Json::Array(pinned)) => { + for p in pinned { + if let Some(n) = s(p.get("provider")) { + out.insert(ItemId::new(ItemKind::Provider, n)); + } + } + } + _ => {} + } + let when = rule.get("when"); + let phase_two = when.and_then(|w| w.get("provider_would_be")); + match phase_two { + Some(Json::String(n)) => { + out.insert(ItemId::new(ItemKind::Provider, n)); + } + Some(Json::Array(list)) => { + for n in list.iter().filter_map(Json::as_str) { + out.insert(ItemId::new(ItemKind::Provider, n)); + } + } + _ => {} + } + if let Some(k) = s(when.and_then(|w| w.get("client"))) { + out.insert(ItemId::new(ItemKind::Key, k)); + } + if let Some(m) = s(when.and_then(|w| w.get("model"))) + && aliases.contains(&m) + { + out.insert(ItemId::new(ItemKind::Alias, m)); + } + if phase_two.is_none() + && let Some(m) = s(rule.get("set").and_then(|w| w.get("model"))) + && aliases.contains(&m) + { + out.insert(ItemId::new(ItemKind::Alias, m)); + } + } + } + ItemKind::Global => { + if let Some(r) = s(units.get(global::DEFAULT_ROUTE)) { + out.insert(ItemId::new(ItemKind::Route, r)); + } + if let Some(k) = s(units.get(global::DEFAULT_KEY)) { + out.insert(ItemId::new(ItemKind::Key, k)); + } + } + _ => {} + } + out +} + +/// 自定义安全规则的项目名拆成分项和规则名 +pub(crate) fn rule_name(name: &str) -> Option<(&str, &str)> { + let (guard, rule) = name.split_once('/')?; + GUARDS.contains(&guard).then_some((guard, rule)) +} diff --git a/crates/tw-pack/src/model/json.rs b/crates/tw-pack/src/model/json.rs new file mode 100644 index 00000000..fb759d5c --- /dev/null +++ b/crates/tw-pack/src/model/json.rs @@ -0,0 +1,131 @@ +//! JSON 与 YAML 之间来回,和按路径摊平一棵 JSON。 +//! +//! 单位的值是 JSON(规范化、键有序);写回配置用的是 YAML 的映射(键按结构体的字段顺序)。 +//! 两边的标量一一对应:字符串、整数、浮点数、布尔、空。 + +use serde_json::Value as Json; +use serde_yaml_ng::{Mapping, Value as Yaml}; + +/// 一个可序列化的值 → JSON。失败是我们自己的类型写坏了 +pub(crate) fn to_json(v: &T) -> Result { + serde_json::to_value(v).map_err(|e| e.to_string()) +} + +/// JSON → YAML。对象的键按 JSON 里的顺序(也就是字母序) +pub(crate) fn to_yaml(v: &Json) -> Yaml { + match v { + Json::Null => Yaml::Null, + Json::Bool(b) => Yaml::Bool(*b), + Json::Number(n) => { + if let Some(u) = n.as_u64() { + Yaml::Number(u.into()) + } else if let Some(i) = n.as_i64() { + Yaml::Number(i.into()) + } else { + Yaml::Number(n.as_f64().unwrap_or(0.0).into()) + } + } + Json::String(s) => Yaml::String(s.clone()), + Json::Array(a) => Yaml::Sequence(a.iter().map(to_yaml).collect()), + Json::Object(m) => Yaml::Mapping( + m.iter() + .map(|(k, v)| (Yaml::String(k.clone()), to_yaml(v))) + .collect(), + ), + } +} + +/// 一个 JSON 对象(单位拼起来的样子)→ 某个配置类型,再写成 YAML 映射:键按结构体的 +/// 字段顺序,默认值不写。读不进那个类型就是这些单位不成形 +pub(crate) fn typed_mapping(fields: Yaml) -> Result<(T, Mapping), String> +where + T: serde::de::DeserializeOwned + serde::Serialize, +{ + let typed: T = serde_yaml_ng::from_value(fields).map_err(|e| e.to_string())?; + match serde_yaml_ng::to_value(&typed).map_err(|e| e.to_string())? { + Yaml::Mapping(m) => Ok((typed, m)), + _ => Err("it does not serialize to a mapping".into()), + } +} + +/// 摊平:对象一层层展开成 `a.b.c` → 值;数组和别的标量是叶子,空对象也是叶子。 +/// 键里的 `~` 和 `.` 转义成 `~0`、`~1` +pub(crate) fn flatten(prefix: &str, v: &Json, out: &mut std::collections::BTreeMap) { + match v { + Json::Object(m) if !m.is_empty() => { + for (k, v) in m { + let k = k.replace('~', "~0").replace('.', "~1"); + let path = if prefix.is_empty() { + k + } else { + format!("{prefix}.{k}") + }; + flatten(&path, v, out); + } + } + other => { + out.insert(prefix.to_string(), other.clone()); + } + } +} + +/// [`flatten`] 反过来。空路径是整棵树本身 +pub(crate) fn unflatten(units: &std::collections::BTreeMap) -> Json { + if let Some(root) = units.get("") { + return root.clone(); + } + let mut root = serde_json::Map::new(); + for (path, v) in units { + let parts: Vec = path + .split('.') + .map(|p| p.replace("~1", ".").replace("~0", "~")) + .collect(); + let mut cur = &mut root; + for (i, p) in parts.iter().enumerate() { + if i + 1 == parts.len() { + cur.insert(p.clone(), v.clone()); + } else { + let next = cur + .entry(p.clone()) + .or_insert_with(|| Json::Object(Default::default())); + if !next.is_object() { + *next = Json::Object(Default::default()); + } + cur = next.as_object_mut().expect("just made it an object"); + } + } + } + Json::Object(root) +} + +/// 映射里的一个键 +pub(crate) fn key(k: &str) -> Yaml { + Yaml::String(k.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn flattening_and_back_gives_the_same_tree() { + for v in [ + json!({"language": "zh", "menubar": {"show": "tokens", "rows": 2}, "list": [1, 2], "empty": {}}), + json!({"a.b": {"c~d": true}}), + json!("just a string"), + ] { + let mut flat = Default::default(); + flatten("", &v, &mut flat); + assert_eq!(unflatten(&flat), v, "{flat:?}"); + } + } + + #[test] + fn numbers_keep_their_kind_through_yaml() { + let v = json!({"u": 3, "i": -2, "f": 1.5}); + let y = to_yaml(&v); + let back: Json = serde_json::to_value(&y).unwrap(); + assert_eq!(back, v); + } +} diff --git a/crates/tw-pack/src/model/mod.rs b/crates/tw-pack/src/model/mod.rs new file mode 100644 index 00000000..ce9efe29 --- /dev/null +++ b/crates/tw-pack/src/model/mod.rs @@ -0,0 +1,533 @@ +//! 一份配置拆成「项目」与「合并单位」,以及反过来把目标状态落回配置文本。 +//! +//! 导入(两方比较)、同步(三方合并)、恢复(按项目挑)都只在这一层上比较:比的是 +//! [`Snapshot`],不是 YAML 原文。原文里的注释、排版、默认值写没写都不算差别。 +//! +//! # 项目 +//! +//! 一个项目是配置里有名字的一样东西([`ItemId`]):上游、出站代理、网关密钥、别名、策略组、 +//! 路由、价目表、自定义安全规则、插件,加上几样没有名字的:上游、路由、插件各自的先后顺序 +//! (顺序有意义:没写路由时按上游的顺序故障转移,插件按顺序运行),全局设置的每一节, +//! Lite 的通用偏好。 +//! +//! # 合并单位 +//! +//! 一个项目里能各自合并的部分([`Item::units`])。值是**规范化**之后的 JSON:按配置的类型 +//! 读进来再写出去,默认值不写,同样的内容总是同样的值。 +//! +//! - 上游:`conn`(地址、协议、密钥、请求头、出站代理、AWS、认证方式)、`models`、 +//! `billing`、`other`(并发、转发客户端身份、余额来源、停用,以及将来新加的字段) +//! - 插件:`script`(数据换成缺省之后的源码)、`settings`(出错时怎么办、范围、设置的值)、 +//! `enabled` +//! - 全局设置、通用偏好:逐个字段,单位名是字段的路径(`failover.pause_secs`)。**等于 +//! 默认值的字段不在里面**,一节全是默认值时这一项就不在快照里 +//! - 其余:一个单位 `all` +//! +//! # 本机设置 +//! +//! 不进快照,[`materialize`] 时保留本机的值:`listen`、`retention`、`sync` 三节,ChatGPT +//! 上游的登录(`oauth`)和登录所得的 `ChatGPT-Account-Id` 请求头,Core 自带的默认插件的 +//! 脚本(它的设置和开关照常比较)。 + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::OnceLock; + +use serde::{Deserialize, Serialize}; +use serde_json::Value as Json; +use tw_types::{Msg, msg}; + +use crate::{Pack, PluginFiles}; + +mod codec; +mod items; +mod json; +mod rename; +mod write; + +pub use codec::{PluginCodec, WholeFile}; +pub use rename::{free_name, rename}; +pub use write::{materialize, materialize_with}; + +/// 配置里属于这台设备、不随导出和同步带走的几节 +pub const LOCAL_SECTIONS: &[&str] = &["listen", "retention", "sync"]; + +/// 合并单位的名字。 +pub mod unit { + /// 整个项目是一个单位 + pub const ALL: &str = "all"; + /// 上游:服务类型、地址、协议、认证方式、密钥、请求头、出站代理、AWS + pub const CONN: &str = "conn"; + /// 上游:模型列表、只用这些模型、手动规格 + pub const MODELS: &str = "models"; + /// 上游:计费方式、价目表 + pub const BILLING: &str = "billing"; + /// 上游:并发上限、转发客户端身份、余额来源、停用 + pub const OTHER: &str = "other"; + /// 插件:数据换成缺省之后的源码 + pub const SCRIPT: &str = "script"; + /// 插件:出错时怎么办、范围、设置的值 + pub const SETTINGS: &str = "settings"; + /// 插件:开着没有 + pub const ENABLED: &str = "enabled"; +} + +/// 全局设置各节的名字([`ItemKind::Global`] 的 `name`)。 +pub mod global { + pub const FAILOVER: &str = "failover"; + pub const SECURITY: &str = "security"; + pub const DEFAULT_ROUTE: &str = "default_route"; + pub const DEFAULT_KEY: &str = "default_key"; + pub const CLIENT_PROBES: &str = "client_probes"; + pub const PRICING: &str = "pricing"; + /// 全部,按这个顺序 + pub const ALL: &[&str] = &[ + FAILOVER, + SECURITY, + DEFAULT_ROUTE, + DEFAULT_KEY, + CLIENT_PROBES, + PRICING, + ]; +} + +/// 自定义安全规则分在哪一项防护下:`security.<分项>.custom` +pub const GUARDS: &[&str] = &["redact", "inspect_tools", "content"]; + +/// 项目的种类。**先后就是排序**:列表、预览里按这个顺序。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ItemKind { + Provider, + Proxy, + /// 网关密钥(配置里的 `clients`) + Key, + Alias, + Group, + Route, + PriceSheet, + /// `name` 是 `<分项>/<规则名>`,如 `content/项目代号` + SecurityRule, + Plugin, + /// 上游的先后。`name` 是空的 + ProviderOrder, + /// 路由的先后。`name` 是空的 + RouteOrder, + /// 插件的先后(运行的顺序)。`name` 是空的 + PluginOrder, + /// `name` 是节名,见 [`global`] + Global, + /// Lite 的通用偏好。`name` 是空的 + ClientPrefs, +} + +impl ItemKind { + pub const ALL: &'static [ItemKind] = &[ + ItemKind::Provider, + ItemKind::Proxy, + ItemKind::Key, + ItemKind::Alias, + ItemKind::Group, + ItemKind::Route, + ItemKind::PriceSheet, + ItemKind::SecurityRule, + ItemKind::Plugin, + ItemKind::ProviderOrder, + ItemKind::RouteOrder, + ItemKind::PluginOrder, + ItemKind::Global, + ItemKind::ClientPrefs, + ]; + + pub fn slug(&self) -> &'static str { + match self { + ItemKind::Provider => "provider", + ItemKind::Proxy => "proxy", + ItemKind::Key => "key", + ItemKind::Alias => "alias", + ItemKind::Group => "group", + ItemKind::Route => "route", + ItemKind::PriceSheet => "price_sheet", + ItemKind::SecurityRule => "security_rule", + ItemKind::Plugin => "plugin", + ItemKind::ProviderOrder => "provider_order", + ItemKind::RouteOrder => "route_order", + ItemKind::PluginOrder => "plugin_order", + ItemKind::Global => "global", + ItemKind::ClientPrefs => "client_prefs", + } + } + + pub fn from_slug(s: &str) -> Option { + ItemKind::ALL.iter().copied().find(|k| k.slug() == s) + } + + /// 一种先后顺序。它们不是用户挑的项目:导入时新加的项目接在后面,恢复、同步时整个比 + pub fn is_order(&self) -> bool { + matches!( + self, + ItemKind::ProviderOrder | ItemKind::RouteOrder | ItemKind::PluginOrder + ) + } + + /// 有名字、可以改名的那几种 + pub fn is_named(&self) -> bool { + !self.is_order() && !matches!(self, ItemKind::Global | ItemKind::ClientPrefs) + } + + /// 这种项目的先后由哪一种顺序管 + pub fn order(&self) -> Option { + match self { + ItemKind::Provider => Some(ItemKind::ProviderOrder), + ItemKind::Route => Some(ItemKind::RouteOrder), + ItemKind::Plugin => Some(ItemKind::PluginOrder), + _ => None, + } + } +} + +/// 一个项目是谁:种类加名字。 +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct ItemId { + pub kind: ItemKind, + pub name: String, +} + +impl ItemId { + pub fn new(kind: ItemKind, name: impl Into) -> Self { + Self { + kind, + name: name.into(), + } + } +} + +impl std::fmt::Display for ItemId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.name.is_empty() { + f.write_str(self.kind.slug()) + } else { + write!(f, "{} `{}`", self.kind.slug(), self.name) + } + } +} + +/// 一个项目:它的合并单位,和它引用的项目。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Item { + /// 单位名 → 规范化的值 + pub units: BTreeMap, + /// 它引用的项目(路由 → 上游、上游 → 出站代理……)。**按单位算出来的**,单位改了要 + /// [`Snapshot::relink`]。被引用的那一项不一定在快照里:引用了不存在的东西,导入时 + /// 按这个说出缺的是什么 + pub refs: BTreeSet, + /// 插件的原文件,**不参与比较**:落盘时优先用它,字节原样;和单位对不上、或者没有时 + /// 按单位重新拼出源码(manifest 那一段按固定的样子写) + #[serde(skip)] + pub files: Option, +} + +/// 比较只看单位和引用:同样的内容从两份文件读出来,原文件的字节可以不同 +impl PartialEq for Item { + fn eq(&self, other: &Self) -> bool { + self.units == other.units && self.refs == other.refs + } +} + +/// 一份配置拆开之后的样子。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Snapshot { + pub items: BTreeMap, +} + +/// 写成 JSON 时是一个列表:`ItemId` 当不了 JSON 对象的键 +impl Serialize for Snapshot { + fn serialize(&self, s: S) -> Result { + #[derive(Serialize)] + struct Entry<'a> { + kind: ItemKind, + name: &'a str, + units: &'a BTreeMap, + #[serde(skip_serializing_if = "BTreeSet::is_empty")] + refs: &'a BTreeSet, + } + s.collect_seq(self.items.iter().map(|(id, it)| Entry { + kind: id.kind, + name: &id.name, + units: &it.units, + refs: &it.refs, + })) + } +} + +impl<'de> Deserialize<'de> for Snapshot { + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + struct Entry { + kind: ItemKind, + name: String, + #[serde(default)] + units: BTreeMap, + #[serde(default)] + refs: BTreeSet, + } + let entries = Vec::::deserialize(d)?; + Ok(Snapshot { + items: entries + .into_iter() + .map(|e| { + ( + ItemId::new(e.kind, e.name), + Item { + units: e.units, + refs: e.refs, + files: None, + }, + ) + }) + .collect(), + }) + } +} + +impl Snapshot { + pub fn get(&self, id: &ItemId) -> Option<&Item> { + self.items.get(id) + } + + /// 某一种的全部项目,按名字 + pub fn of_kind(&self, kind: ItemKind) -> impl Iterator { + self.items.iter().filter(move |(id, _)| id.kind == kind) + } + + /// 这一项连同它(直接或间接)引用的、快照里有的项目。导出所选项目时用:路由带上 + /// 它的上游,上游带上它的出站代理 + pub fn closure(&self, roots: &[ItemId]) -> BTreeSet { + let mut out = BTreeSet::new(); + let mut todo: Vec = roots.to_vec(); + while let Some(id) = todo.pop() { + let Some(item) = self.items.get(&id) else { + continue; + }; + if !out.insert(id) { + continue; + } + todo.extend(item.refs.iter().cloned()); + } + out + } + + /// 按单位重算每一项的引用。改了单位之后(合并、改名)调它 + pub fn relink(&mut self) { + items::relink(&mut self.items); + } + + /// 只留下这几项,**顺序项目跟着裁**:只剩留下来的那些名字 + pub fn retain(&mut self, keep: &BTreeSet) { + let names = |kind: ItemKind| -> BTreeSet { + keep.iter() + .filter(|id| id.kind == kind) + .map(|id| id.name.clone()) + .collect() + }; + let mut orders = BTreeMap::new(); + for kind in [ItemKind::Provider, ItemKind::Route, ItemKind::Plugin] { + orders.insert(kind.order().unwrap_or(kind), names(kind)); + } + self.items.retain(|id, item| { + if let Some(allowed) = orders.get(&id.kind) { + if let Some(Json::Array(list)) = item.units.get_mut(unit::ALL) { + list.retain(|n| n.as_str().is_some_and(|n| allowed.contains(n))); + return !list.is_empty(); + } + return false; + } + keep.contains(id) + }); + } +} + +/// 拆不开、或者落不回去。**英文只写一遍**:`Display` 就是 [`ModelError::msg`] 的原句。 +#[derive(Debug, Clone, thiserror::Error)] +pub enum ModelError { + /// 配置读不进来(语法错、字段不认识)。里面是和换入配置时同一句话 + #[error("{}", self.msg())] + Config(Box), + /// 配置的格式版本比这一份 Core 新 + #[error("{}", self.msg())] + TooNew { schema: u32 }, + /// 一项的单位拼不回配置里的样子(同步合并出来的东西不成形) + #[error("{}", self.msg())] + Shape { item: String, detail: String }, + /// 按名字改配置时没成 + #[error("{}", self.msg())] + Edit(String, Box), + /// 写完读回来和要的不一样。是我们自己的错 + #[error("{}", self.msg())] + Verify { detail: String }, +} + +impl ModelError { + pub fn msg(&self) -> Msg { + match self { + ModelError::Config(r) => r.msg(), + ModelError::TooNew { schema } => msg!( + "pack.schema_too_new", schema = schema, supported = tw_config::SCHEMA_VERSION => + "The configuration is schema version {schema}, and this version supports up to \ + {supported}. Update ThinkWatch Lite first." + ), + ModelError::Shape { item, detail } => msg!( + "pack.item_shape", item = item, detail = detail => + "{item} cannot be written into the configuration: {detail}" + ), + ModelError::Edit(_, m) => (**m).clone(), + ModelError::Verify { detail } => msg!( + "pack.verify_failed", detail = detail => + "The configuration that was put together does not read back as intended \ + ({detail}), so nothing was written." + ), + } + } + + /// 读不进来是因为它由更新的版本写的(不认识的字段、取值,或者格式版本更大) + pub fn is_too_new(&self) -> bool { + match self { + ModelError::TooNew { .. } => true, + ModelError::Config(r) => matches!( + r.message.code.as_str(), + "config.unknown_field" | "config.unknown_variant" + ), + _ => false, + } + } +} + +impl From for ModelError { + fn from(e: tw_config::edit::EditError) -> Self { + ModelError::Edit(e.to_string(), Box::new(e.msg())) + } +} + +impl From for ModelError { + fn from(e: tw_yaml::PatchError) -> Self { + ModelError::Edit(e.to_string(), Box::new(e.msg())) + } +} + +// ─────────────────────────────────────────────────────────── 插件的拆法 + +static CODEC: OnceLock> = OnceLock::new(); + +/// 装上插件源码的拆法([`PluginCodec`])。**进程里装一次**:Core 启动时装上真的那一套 +/// (它要编插件的那几个 crate);没装时按 [`WholeFile`] 整份比较。装过了返回 false +pub fn install_codec(codec: Box) -> bool { + CODEC.set(codec).is_ok() +} + +/// 此刻用的拆法 +pub fn codec() -> &'static dyn PluginCodec { + match CODEC.get() { + Some(c) => c.as_ref(), + None => &WholeFile, + } +} + +// ─────────────────────────────────────────────────────────── 拆 + +/// 把一个包拆成项目。本机设置不在里面。用进程里装的插件拆法([`install_codec`]) +pub fn snapshot(pack: &Pack) -> Result { + snapshot_with(pack, codec()) +} + +/// 同 [`snapshot`],插件拆法由调用方给 +pub fn snapshot_with(pack: &Pack, codec: &dyn PluginCodec) -> Result { + let cfg = parse(&pack.config_yaml)?; + let mut items = items::of_config(&cfg, pack, codec)?; + items::relink(&mut items); + Ok(Snapshot { items }) +} + +/// 读一份配置原文,**不做整份校验**:一个只有一个上游的部分包没有网关密钥,也没有 +/// 控制面的钥匙。本机那几节先去掉再读,同步那一节的写法这里不必认得 +pub(crate) fn parse(text: &str) -> Result { + let reject = || -> ModelError { + match tw_config::try_parse(text) { + Err(r) if r.stage != tw_config::Stage::Semantics => ModelError::Config(Box::new(r)), + _ => ModelError::Verify { + detail: "the configuration could not be read".into(), + }, + } + }; + let mut doc: serde_yaml_ng::Value = serde_yaml_ng::from_str(text).map_err(|_| reject())?; + if doc.is_null() { + doc = serde_yaml_ng::Value::Mapping(Default::default()); + } + if let serde_yaml_ng::Value::Mapping(m) = &mut doc { + for k in LOCAL_SECTIONS { + m.remove(*k); + } + } + let cfg: tw_config::Config = serde_yaml_ng::from_value(doc).map_err(|e| { + // 本机那几节以外读不进来:原文整份读一遍,借它的行号和那句带码的话 + match tw_config::try_parse(text) { + Err(r) if r.stage != tw_config::Stage::Semantics => ModelError::Config(Box::new(r)), + _ => ModelError::Config(Box::new(tw_config::Rejected { + stage: tw_config::Stage::Schema, + message: Box::new(msg!(tw_config::reload::UNPARSABLE, detail = e => "{detail}")), + line: None, + column: None, + excerpt: None, + })), + } + })?; + if cfg.version > tw_config::SCHEMA_VERSION { + return Err(ModelError::TooNew { + schema: cfg.version, + }); + } + Ok(cfg) +} + +/// [`Pack::content_id`] +pub(crate) fn content_id(pack: &Pack) -> String { + let hash = match snapshot(pack) { + Ok(s) => blake3::hash( + serde_json::to_string(&normalized(&s)) + .unwrap_or_default() + .as_bytes(), + ), + Err(_) => { + let mut h = blake3::Hasher::new(); + h.update(pack.config_yaml.as_bytes()); + for (id, f) in &pack.plugins { + h.update(id.as_bytes()); + h.update(&f.script); + } + if let Some(p) = &pack.client_prefs { + h.update(p.to_string().as_bytes()); + } + h.finalize() + } + }; + hash.to_hex()[..12].to_string() +} + +/// 只留单位(引用是算出来的),全局设置里等于默认值的单位去掉、空了的项目去掉 —— +/// 同步合并出来的快照可能把默认值写明了,落回配置之后它们读出来就是没写 +pub fn normalized(s: &Snapshot) -> Snapshot { + let mut out = s.clone(); + for (id, item) in out.items.iter_mut() { + item.refs.clear(); + item.files = None; + if id.kind == ItemKind::Global { + item.units + .retain(|path, v| !items::is_global_default(path, v)); + } + } + out.items.retain(|id, item| { + !(matches!(id.kind, ItemKind::Global | ItemKind::ClientPrefs) && item.units.is_empty()) + }); + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/tw-pack/src/model/rename.rs b/crates/tw-pack/src/model/rename.rs new file mode 100644 index 00000000..3a84ec3e --- /dev/null +++ b/crates/tw-pack/src/model/rename.rs @@ -0,0 +1,241 @@ +//! 在快照里给一个项目改名,引用它的地方跟着改。 +//! +//! 和按名字编辑配置时的改名(`tw_config::refs`)是同一份规矩,只是改的是单位而不是原文: +//! 导入时选「改名导入」、同步时选「两者都保留」,改名的是配置包里的那一份,包里引用它的 +//! 路由、别名、分组随之改用新名称。 + +use serde_json::Value as Json; + +use super::items::rule_name; +use super::{ItemId, ItemKind, Snapshot, global, unit}; + +/// 把 `id` 改名成 `new_name`,连同快照里引用它的地方。没有这一项、名字没变、这种项目 +/// 没有名字(顺序、全局设置、通用偏好)时什么都不做。新名字已经被占了也不做:调用方 +/// 先挑一个没人用的([`free_name`])。 +/// +/// 自定义安全规则的 `new_name` 可以只写规则名(分项不变),也可以写成 `<分项>/<规则名>` +pub fn rename(snap: &mut Snapshot, id: &ItemId, new_name: &str) { + if !id.kind.is_named() || id.name == new_name { + return; + } + let new_name = match id.kind { + ItemKind::SecurityRule if !new_name.contains('/') => match rule_name(&id.name) { + Some((guard, _)) => format!("{guard}/{new_name}"), + None => return, + }, + _ => new_name.to_string(), + }; + let new_id = ItemId::new(id.kind, new_name.clone()); + if snap.items.contains_key(&new_id) { + return; + } + let Some(item) = snap.items.remove(id) else { + return; + }; + snap.items.insert(new_id, item); + let old = id.name.as_str(); + let new = new_name.as_str(); + + for (other, item) in snap.items.iter_mut() { + let all = item.units.get_mut(unit::ALL); + match (id.kind, other.kind) { + (ItemKind::Provider, ItemKind::Route) => { + if let Some(all) = all { + for rule in rules(all) { + match rule.get_mut("to") { + Some(Json::Array(pinned)) => { + for p in pinned { + swap(p.get_mut("provider"), old, new); + } + } + to => swap(to, old, new), + } + if let Some(when) = rule.get_mut("when") { + swap_one_or_many(when.get_mut("provider_would_be"), old, new); + } + } + } + } + (ItemKind::Provider, ItemKind::Group) => { + if let Some(all) = all { + if let Some(Json::Array(members)) = all.get_mut("providers") { + for m in members { + match m { + Json::String(_) => swap(Some(m), old, new), + Json::Object(o) => swap(o.get_mut("name"), old, new), + _ => {} + } + } + } + swap(all.get_mut("selected"), old, new); + } + } + (ItemKind::Provider, ItemKind::ProviderOrder) + | (ItemKind::Route, ItemKind::RouteOrder) + | (ItemKind::Plugin, ItemKind::PluginOrder) => { + if let Some(Json::Array(list)) = all { + for n in list { + swap(Some(n), old, new); + } + } + } + (ItemKind::Proxy, ItemKind::Provider) => { + swap( + item.units + .get_mut(unit::CONN) + .and_then(|c| c.get_mut("proxy")), + old, + new, + ); + } + (ItemKind::PriceSheet, ItemKind::Provider) => { + swap( + item.units + .get_mut(unit::BILLING) + .and_then(|c| c.get_mut("pricing")), + old, + new, + ); + } + (ItemKind::Key, ItemKind::Route) => { + if let Some(all) = all { + for rule in rules(all) { + swap( + rule.get_mut("when").and_then(|w| w.get_mut("client")), + old, + new, + ); + } + } + } + (ItemKind::Key, ItemKind::Global) if other.name == global::DEFAULT_KEY => { + swap(item.units.get_mut(global::DEFAULT_KEY), old, new); + } + (ItemKind::Alias, ItemKind::Key) => { + if let Some(Json::Array(allow)) = all.and_then(|a| a.get_mut("allow")) { + for m in allow { + swap(Some(m), old, new); + } + } + } + (ItemKind::Alias, ItemKind::Route) => { + if let Some(all) = all { + for rule in rules(all) { + let phase_two = rule + .get("when") + .is_some_and(|w| w.get("provider_would_be").is_some()); + swap( + rule.get_mut("when").and_then(|w| w.get_mut("model")), + old, + new, + ); + if !phase_two { + swap( + rule.get_mut("set").and_then(|s| s.get_mut("model")), + old, + new, + ); + } + } + } + } + (ItemKind::Group, ItemKind::Route) => { + if let Some(all) = all { + for rule in rules(all) { + swap(rule.get_mut("to"), old, new); + } + } + } + (ItemKind::Route, ItemKind::Key) => { + swap(all.and_then(|a| a.get_mut("route")), old, new); + } + _ => {} + } + } + + // 默认路由:没写明时说的是叫「默认」的那条。改的正是它,要把新名字写明;改成的正是 + // 「默认」,写明的那一项就不用了 + if id.kind == ItemKind::Route { + let at = ItemId::new(ItemKind::Global, global::DEFAULT_ROUTE); + let current = snap + .items + .get(&at) + .and_then(|i| i.units.get(global::DEFAULT_ROUTE)) + .and_then(Json::as_str) + .unwrap_or(tw_engine::DEFAULT_ROUTE) + .to_string(); + if current == old { + if new == tw_engine::DEFAULT_ROUTE { + snap.items.remove(&at); + } else { + snap.items.entry(at).or_default().units.insert( + global::DEFAULT_ROUTE.to_string(), + Json::String(new.to_string()), + ); + } + } + } + // 默认密钥同理 + if id.kind == ItemKind::Key { + let at = ItemId::new(ItemKind::Global, global::DEFAULT_KEY); + let written = snap + .items + .get(&at) + .and_then(|i| i.units.get(global::DEFAULT_KEY)) + .is_some(); + if !written && old == tw_config::DEFAULT_KEY { + snap.items.entry(at).or_default().units.insert( + global::DEFAULT_KEY.to_string(), + Json::String(new.to_string()), + ); + } else if written && new == tw_config::DEFAULT_KEY { + let now = snap + .items + .get(&at) + .and_then(|i| i.units.get(global::DEFAULT_KEY)); + if now.and_then(Json::as_str) == Some(new) { + snap.items.remove(&at); + } + } + } + snap.relink(); +} + +/// `base` 没被占就是它,被占了是「base (2)」「base (3)」…… +pub fn free_name(snap: &Snapshot, kind: ItemKind, base: &str) -> String { + let taken = |n: &str| snap.items.contains_key(&ItemId::new(kind, n)); + if !taken(base) { + return base.to_string(); + } + (2..) + .map(|i| format!("{base} ({i})")) + .find(|n| !taken(n)) + .expect("an unbounded range always finds one") +} + +fn rules(all: &mut Json) -> impl Iterator { + all.get_mut("rules") + .and_then(Json::as_array_mut) + .into_iter() + .flatten() +} + +/// 这个位置上的字符串正是 `old` 就换成 `new` +fn swap(at: Option<&mut Json>, old: &str, new: &str) { + if let Some(v) = at + && v.as_str() == Some(old) + { + *v = Json::String(new.to_string()); + } +} + +fn swap_one_or_many(at: Option<&mut Json>, old: &str, new: &str) { + match at { + Some(Json::Array(list)) => { + for v in list { + swap(Some(v), old, new); + } + } + other => swap(other, old, new), + } +} diff --git a/crates/tw-pack/src/model/tests.rs b/crates/tw-pack/src/model/tests.rs new file mode 100644 index 00000000..a09ce6c1 --- /dev/null +++ b/crates/tw-pack/src/model/tests.rs @@ -0,0 +1,1015 @@ +//! 拆开、落回、改名。表驱动:每一种项目的每一种改法,落回去再拆开都是要的那个样子。 + +use std::collections::BTreeMap; + +use serde_json::{Value as Json, json}; + +use super::*; +use crate::{Manifest, Pack, PackKind, PackOrigin, PluginFiles}; + +const KEY: &str = "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00"; + +/// 一份什么都有的配置。注释散在各处:没改的项目落回去之后它们还在 +fn rich() -> String { + format!( + r#"version: 1 +listen: + control: + key: {KEY} + gateway: + port: 9000 +retention: + body_days: 3 +clients: + - name: default + key: tw-aaa + # 给 Codex 的 + - name: codex + key: tw-bbb + route: 长上下文 + client: codex + allow: [fast] +proxies: + - name: hk + type: socks5h + addr: 127.0.0.1:7890 +providers: + # 官方直连 + - name: 官方 + base_url: https://api.anthropic.com # 不走代理 + key: sk-a + proxy: direct + headers: + X-Second: b + X-First: a + - name: relay + base_url: https://relay.example/v1 + key: sk-b + proxy: hk + pricing: 中转 + models: [m1] + max_concurrent: 4 + - name: chatgpt + base_url: https://chatgpt.com/backend-api/codex + oauth: + refresh: rt-1 + endpoint: https://auth.openai.com/oauth/token + client_id: app_EMoamEEZ73f0CkXaXp7hrann + headers: + ChatGPT-Account-Id: acct-1 +pricing: + auto_update: false + sheets: + - name: 中转 + multiplier: 0.5 +failover: + pause_secs: 120 +security: + redact: + mode: enforce + custom: + - name: 项目代号 + pattern: 北极星 + content: + custom: + - name: 脏话 + pattern: xx +aliases: + fast: [claude-haiku, gpt-mini] +groups: + - name: pool + type: fallback + providers: [官方, relay] +routes: + - name: default + rules: + - name: 兜底 + to: pool + - name: 长上下文 + rules: + - name: big + when: {{ input_tokens: '>200k', client: codex }} + to: relay +default_key: default +"# + ) +} + +fn pack(text: &str) -> Pack { + Pack { + manifest: Manifest::new(PackKind::Full, PackOrigin::Ui), + config_yaml: text.to_string(), + plugins: BTreeMap::new(), + client_prefs: None, + } +} + +fn id(kind: ItemKind, name: &str) -> ItemId { + ItemId::new(kind, name) +} + +/// 插件源码的测试拆法:第一行是 `// data: `,其余是代码。名字带 `steer` 的要批准 +struct Fake { + shipped: BTreeMap, +} + +impl Fake { + fn new() -> Self { + Self { + shipped: BTreeMap::from([( + "reply-language".to_string(), + "// data: {\"lang\":\"\"}\nshipped code v1\n".to_string(), + )]), + } + } +} + +impl PluginCodec for Fake { + fn split(&self, source: &str) -> Option<(String, Json)> { + let (first, rest) = source.split_once('\n')?; + let data: Json = serde_json::from_str(first.strip_prefix("// data: ")?).ok()?; + Some((format!("// data: null\n{rest}"), data)) + } + fn join(&self, source: &str, data: &Json) -> Option { + let (_, rest) = source.split_once('\n')?; + Some(format!("// data: {data}\n{rest}")) + } + fn shipped(&self, id: &str) -> Option { + self.shipped.get(id).cloned() + } + fn needs_approval(&self, source: &str) -> bool { + source.contains("steer") + } +} + +fn snap(p: &Pack) -> Snapshot { + snapshot_with(p, &Fake::new()).unwrap_or_else(|e| panic!("{e}\n{}", p.config_yaml)) +} + +fn mat(local: &Pack, target: &Snapshot) -> Pack { + materialize_with(local, target, &Fake::new()).unwrap_or_else(|e| panic!("{e}")) +} + +fn without_orders(s: &Snapshot) -> Snapshot { + let mut s = s.clone(); + s.items.retain(|id, _| !id.kind.is_order()); + s +} + +// ─────────────────────────────────────────────────────────── 拆 + +#[test] +fn every_named_thing_is_an_item_and_local_settings_are_not() { + let s = snap(&pack(&rich())); + let ids: Vec = s.items.keys().map(|i| i.to_string()).collect(); + for want in [ + "provider `官方`", + "provider `relay`", + "provider `chatgpt`", + "proxy `hk`", + "key `default`", + "key `codex`", + "alias `fast`", + "group `pool`", + "route `default`", + "route `长上下文`", + "price_sheet `中转`", + "security_rule `redact/项目代号`", + "security_rule `content/脏话`", + "provider_order", + "route_order", + "global `failover`", + "global `security`", + "global `pricing`", + ] { + assert!(ids.contains(&want.to_string()), "{want} 不在:{ids:?}"); + } + // 写成默认值的那一节不算(default_key: default 就是没写) + assert!(!ids.iter().any(|i| i.contains("default_key")), "{ids:?}"); + let all = serde_json::to_string(&s).unwrap(); + for local in [KEY, "9000", "body_days", "rt-1", "acct-1"] { + assert!(!all.contains(local), "本机设置进了快照:{local}"); + } +} + +#[test] +fn an_upstream_splits_into_four_units_by_what_its_fields_are_about() { + let s = snap(&pack(&rich())); + let relay = &s.items[&id(ItemKind::Provider, "relay")]; + assert_eq!( + relay.units.keys().collect::>(), + ["billing", "conn", "models", "other"] + ); + assert_eq!( + relay.units["conn"], + json!({"base_url": "https://relay.example/v1", "key": "sk-b", "proxy": "hk"}) + ); + assert_eq!(relay.units["models"], json!({"models": ["m1"]})); + assert_eq!(relay.units["billing"], json!({"pricing": "中转"})); + assert_eq!(relay.units["other"], json!({"max_concurrent": 4})); + // 写明的默认值(proxy: direct)和没写一样;请求头按写的顺序 + let official = &s.items[&id(ItemKind::Provider, "官方")]; + assert_eq!( + official.units["conn"], + json!({"base_url": "https://api.anthropic.com", "key": "sk-a", + "headers": [["X-Second", "b"], ["X-First", "a"]]}) + ); + // ChatGPT 的登录和账户 ID 请求头不在里面 + let chatgpt = &s.items[&id(ItemKind::Provider, "chatgpt")]; + assert_eq!( + chatgpt.units["conn"], + json!({"base_url": "https://chatgpt.com/backend-api/codex"}) + ); +} + +#[test] +fn references_point_at_what_each_item_uses() { + let s = snap(&pack(&rich())); + let refs = |kind, name: &str| -> Vec { + s.items[&id(kind, name)] + .refs + .iter() + .map(|r| r.to_string()) + .collect() + }; + assert_eq!( + refs(ItemKind::Provider, "relay"), + ["proxy `hk`", "price_sheet `中转`"] + ); + assert_eq!( + refs(ItemKind::Key, "codex"), + ["alias `fast`", "route `长上下文`"] + ); + assert_eq!( + refs(ItemKind::Group, "pool"), + ["provider `relay`", "provider `官方`"] + ); + assert_eq!(refs(ItemKind::Route, "default"), ["group `pool`"]); + assert_eq!( + refs(ItemKind::Route, "长上下文"), + ["provider `relay`", "key `codex`"] + ); + // 选一条路由导出:带上它的上游、上游的代理和价目表、按它分流的密钥 + let picked: Vec = s + .closure(&[id(ItemKind::Route, "长上下文")]) + .iter() + .map(|i| i.to_string()) + .collect(); + assert_eq!( + picked, + [ + "provider `relay`", + "proxy `hk`", + "key `codex`", + "alias `fast`", + "route `长上下文`", + "price_sheet `中转`" + ] + ); +} + +/// 注释、排版、写没写默认值都不是差别;本机设置也不是 +#[test] +fn the_same_content_written_differently_is_the_same_snapshot_and_id() { + let a = pack(&rich()); + let mut b = pack( + &rich() + .replace(" # 官方直连\n", "") + .replace(" proxy: direct\n", "") + .replace(" gateway:\n port: 9000\n", "") + .replace("retention:\n body_days: 3\n", "") + .replace("default_key: default\n", "") + .replace("rt-1", "rt-2-after-a-rotation"), + ); + assert_eq!(snap(&a), snap(&b)); + assert_eq!(a.content_id(), b.content_id()); + assert_eq!(a.content_id().len(), 12); + b.config_yaml = b.config_yaml.replace("sk-b", "sk-changed"); + assert_ne!(a.content_id(), b.content_id()); +} + +#[test] +fn global_settings_hold_only_what_differs_from_the_default() { + let s = snap(&pack(&rich())); + assert_eq!( + s.items[&id(ItemKind::Global, "failover")].units, + BTreeMap::from([("failover.pause_secs".to_string(), json!(120))]) + ); + assert_eq!( + s.items[&id(ItemKind::Global, "security")].units, + BTreeMap::from([("security.redact.mode".to_string(), json!("enforce"))]) + ); + assert_eq!( + s.items[&id(ItemKind::Global, "pricing")].units, + BTreeMap::from([("pricing.auto_update".to_string(), json!(false))]) + ); + for (path, v, default) in [ + ("failover.pause_secs", json!(60), true), + ("failover.pause_secs", json!(61), false), + ("security.redact.mode", json!("observe"), true), + ("security.content.mode", json!("off"), false), + ("client_probes.titling", json!("intercept"), false), + ("pricing.auto_update", json!(true), true), + ("default_route", json!("default"), true), + ("default_route", json!("other"), false), + ("default_key", json!("default"), true), + ] { + assert_eq!(items::is_global_default(path, &v), default, "{path} = {v}"); + } +} + +#[test] +fn a_pack_from_a_newer_version_is_too_new() { + for text in [ + "version: 1\nsomething_new: true\n", + "version: 1\nproviders:\n - { name: a, base_url: https://a, balance: unheard_of }\n", + ] { + let e = snapshot_with(&pack(text), &Fake::new()).unwrap_err(); + assert!(e.is_too_new(), "{text}: {e:?}"); + } + let e = snapshot_with(&pack("version: 99\n"), &Fake::new()).unwrap_err(); + assert!(e.is_too_new()); + assert_eq!(e.msg().code, "pack.schema_too_new"); + // 读不成 YAML 的不算太新 + let e = snapshot_with(&pack("version: 1\nproviders: [\n"), &Fake::new()).unwrap_err(); + assert!(!e.is_too_new()); + // 只有一个上游的部分包:没有网关密钥、没有钥匙,照样拆得开 + snap(&pack( + "version: 1\nproviders:\n - { name: a, base_url: https://a.example }\n", + )); + // 同步那一节这里不必认得 + snap(&pack( + "version: 1\nsync:\n device_id: x\n whatever: [1]\n", + )); +} + +#[test] +fn a_snapshot_survives_json() { + let s = snap(&pack(&rich())); + let back: Snapshot = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap(); + assert_eq!(back, s); +} + +// ─────────────────────────────────────────────────────────── 落回 + +/// 原样落回:一个字节都不变 +#[test] +fn materializing_a_config_onto_itself_changes_nothing() { + let p = pack(&rich()); + let out = mat(&p, &snap(&p)); + assert_eq!(out.config_yaml, p.config_yaml); +} + +/// 改一处:别的原样,注释也在;本机设置和 ChatGPT 的登录还在 +#[test] +fn changing_one_item_leaves_the_others_byte_for_byte() { + let p = pack(&rich()); + let mut t = snap(&p); + t.items + .get_mut(&id(ItemKind::Provider, "relay")) + .unwrap() + .units + .insert( + "other".into(), + json!({"max_concurrent": 8, "disabled": true}), + ); + let out = mat(&p, &t); + assert!( + out.config_yaml.contains(" max_concurrent: 8\n"), + "{}", + out.config_yaml + ); + for kept in [ + " # 官方直连\n", + "base_url: https://api.anthropic.com # 不走代理\n", + " # 给 Codex 的\n", + " port: 9000\n", + " body_days: 3\n", + " refresh: rt-1\n", + " ChatGPT-Account-Id: acct-1\n", + " proxy: direct\n", + ] { + assert!( + out.config_yaml.contains(kept), + "{kept:?} 没了:\n{}", + out.config_yaml + ); + } + assert_eq!(normalized(&snap(&out)), normalized(&t)); + tw_config::try_parse(&out.config_yaml).unwrap_or_else(|e| panic!("{e}\n{}", out.config_yaml)); +} + +/// 一种项目一张表:加、删、改,落回去再拆开就是要的样子,配置照样过得了校验 +#[test] +fn every_kind_of_change_lands_as_intended() { + type Change = fn(&mut Snapshot); + let cases: Vec<(&str, Change)> = vec![ + ("add an upstream", |s| { + s.items.insert( + ItemId::new(ItemKind::Provider, "new"), + Item { + units: BTreeMap::from([ + ( + "conn".into(), + json!({"base_url": "https://new.example", "key": "sk-n"}), + ), + ("models".into(), json!({})), + ("billing".into(), json!({"billing": "free"})), + ("other".into(), json!({})), + ]), + ..Default::default() + }, + ); + }), + ("drop an upstream nobody uses", |s| { + s.items.remove(&ItemId::new(ItemKind::Provider, "chatgpt")); + }), + ("change an upstream's headers and order", |s| { + let p = s + .items + .get_mut(&ItemId::new(ItemKind::Provider, "官方")) + .unwrap(); + p.units.insert( + "conn".into(), + json!({"base_url": "https://api.anthropic.com", "key": "sk-new", + "headers": [["X-First", "a"], ["X-Third", "c"]]}), + ); + }), + ("add a proxy", |s| { + s.items.insert( + ItemId::new(ItemKind::Proxy, "sg"), + Item { + units: BTreeMap::from([( + "all".into(), + json!({"type": "http", "addr": "10.0.0.1:8080"}), + )]), + ..Default::default() + }, + ); + }), + ("change a key", |s| { + s.items + .get_mut(&ItemId::new(ItemKind::Key, "default")) + .unwrap() + .units + .insert("all".into(), json!({"key": "tw-zzz", "max_concurrent": 2})); + }), + ("drop an alias and its use", |s| { + s.items.remove(&ItemId::new(ItemKind::Alias, "fast")); + s.items + .get_mut(&ItemId::new(ItemKind::Key, "codex")) + .unwrap() + .units + .insert( + "all".into(), + json!({"key": "tw-bbb", "route": "长上下文", "client": "codex"}), + ); + }), + ("add an alias", |s| { + s.items.insert( + ItemId::new(ItemKind::Alias, "big"), + Item { + units: BTreeMap::from([("all".into(), json!(["claude-opus"]))]), + ..Default::default() + }, + ); + }), + ("change a group", |s| { + s.items + .get_mut(&ItemId::new(ItemKind::Group, "pool")) + .unwrap() + .units + .insert( + "all".into(), + json!({"type": "load-balance", "providers": ["官方", {"name": "relay", "weight": 3}]}), + ); + }), + ("add a route and reorder", |s| { + s.items.insert( + ItemId::new(ItemKind::Route, "a-first"), + Item { + units: BTreeMap::from([( + "all".into(), + json!({"rules": [{"name": "all", "to": "官方"}]}), + )]), + ..Default::default() + }, + ); + s.items.insert( + ItemId::new(ItemKind::RouteOrder, ""), + Item { + units: BTreeMap::from([( + "all".into(), + json!(["长上下文", "a-first", "default"]), + )]), + ..Default::default() + }, + ); + }), + ("reorder upstreams", |s| { + s.items.insert( + ItemId::new(ItemKind::ProviderOrder, ""), + Item { + units: BTreeMap::from([("all".into(), json!(["chatgpt", "relay", "官方"]))]), + ..Default::default() + }, + ); + }), + ("change a price sheet", |s| { + s.items + .get_mut(&ItemId::new(ItemKind::PriceSheet, "中转")) + .unwrap() + .units + .insert("all".into(), json!({"multiplier": 0.8})); + }), + ("add and drop custom rules", |s| { + s.items + .remove(&ItemId::new(ItemKind::SecurityRule, "content/脏话")); + s.items.insert( + ItemId::new(ItemKind::SecurityRule, "inspect_tools/rm"), + Item { + units: BTreeMap::from([("all".into(), json!({"pattern": "rm -rf"}))]), + ..Default::default() + }, + ); + }), + ("change and reset global fields", |s| { + let f = s + .items + .get_mut(&ItemId::new(ItemKind::Global, "failover")) + .unwrap(); + f.units.clear(); + f.units + .insert("failover.idle_timeout_secs".into(), json!(600)); + s.items.remove(&ItemId::new(ItemKind::Global, "pricing")); + s.items.insert( + ItemId::new(ItemKind::Global, "security"), + Item { + units: BTreeMap::from([ + ("security.content.mode".into(), json!("enforce")), + ("security.redact.actions.jwt".into(), json!("record")), + ]), + ..Default::default() + }, + ); + s.items.insert( + ItemId::new(ItemKind::Global, "client_probes"), + Item { + units: BTreeMap::from([("client_probes.titling".into(), json!("forward"))]), + ..Default::default() + }, + ); + }), + ("set the default route and key", |s| { + s.items.insert( + ItemId::new(ItemKind::Global, "default_route"), + Item { + units: BTreeMap::from([("default_route".into(), json!("长上下文"))]), + ..Default::default() + }, + ); + s.items.insert( + ItemId::new(ItemKind::Global, "default_key"), + Item { + units: BTreeMap::from([("default_key".into(), json!("codex"))]), + ..Default::default() + }, + ); + }), + ("an explicit default is the same as none", |s| { + s.items.insert( + ItemId::new(ItemKind::Global, "client_probes"), + Item { + units: BTreeMap::from([("client_probes.warmup".into(), json!("intercept"))]), + ..Default::default() + }, + ); + }), + ]; + for (what, change) in cases { + let p = pack(&rich()); + let mut t = snap(&p); + change(&mut t); + t.relink(); + let out = materialize_with(&p, &t, &Fake::new()).unwrap_or_else(|e| panic!("{what}: {e}")); + let got = normalized(&snap(&out)); + assert_eq!( + without_orders(&got), + without_orders(&normalized(&t)), + "{what}:\n{}", + out.config_yaml + ); + // 目标里列着的顺序照着排;没列的(新加的上游)接在后面 + for (oid, o) in t.items.iter().filter(|(i, _)| i.kind.is_order()) { + let have = got.items[oid].units["all"].as_array().unwrap(); + let want: Vec<&Json> = o.units["all"] + .as_array() + .unwrap() + .iter() + .filter(|n| have.contains(n)) + .collect(); + let have: Vec<&Json> = have.iter().take(want.len()).collect(); + assert_eq!(have, want, "{what}: {oid}"); + } + tw_config::try_parse(&out.config_yaml) + .unwrap_or_else(|e| panic!("{what}: {e}\n{}", out.config_yaml)); + // 本机设置都还在;ChatGPT 那一家还在的话,它的登录也在 + // 注释也在:走的是按项目改原文那条路,不是整份重写 + let mut kept = vec![ + " port: 9000\n", + " body_days: 3\n", + KEY, + " # 给 Codex 的\n", + " # 官方直连\n", + ]; + if t.items.contains_key(&id(ItemKind::Provider, "chatgpt")) { + kept.push(" refresh: rt-1\n"); + } + for kept in kept { + assert!( + out.config_yaml.contains(kept), + "{what}: {kept:?} 没了\n{}", + out.config_yaml + ); + } + } +} + +/// 按项目改不动的写法(行内的一节删不了键):整份重写,内容照样对 +#[test] +fn a_shape_the_edits_cannot_touch_is_rewritten_whole() { + let text = format!( + "version: 1\nlisten: {{ control: {{ key: {KEY} }} }}\nclients: [{{ name: default, key: tw-a }}]\nfailover: {{ pause_secs: 120, idle_timeout_secs: 600 }}\n" + ); + let p = pack(&text); + let mut t = snap(&p); + t.items + .get_mut(&id(ItemKind::Global, "failover")) + .unwrap() + .units + .remove("failover.idle_timeout_secs"); + let out = mat(&p, &t); + assert_eq!( + normalized(&snap(&out)), + normalized(&t), + "{}", + out.config_yaml + ); + assert!(out.config_yaml.contains(KEY)); + tw_config::try_parse(&out.config_yaml).unwrap(); +} + +/// 从空的配置开始落:导出所选项目就是这么生成配置包的 +#[test] +fn materializing_onto_an_empty_config_builds_just_those_items() { + let full = snap(&pack(&rich())); + let mut picked = full.clone(); + picked.retain(&full.closure(&[id(ItemKind::Route, "长上下文")])); + let out = mat(&pack("version: 1\n"), &picked); + assert_eq!( + normalized(&snap(&out)), + normalized(&picked), + "{}", + out.config_yaml + ); + assert!(!out.config_yaml.contains("官方"), "{}", out.config_yaml); +} + +/// ChatGPT 账号上游:落到别的设备上时没有登录;落回本机时留着本机的登录 +#[test] +fn a_chatgpt_upstream_keeps_the_login_of_the_device_it_lands_on() { + let p = pack(&rich()); + let mut t = snap(&p); + t.items + .get_mut(&id(ItemKind::Provider, "chatgpt")) + .unwrap() + .units + .insert("other".into(), json!({"disabled": true})); + let out = mat(&p, &t); + let cfg = tw_config::try_parse(&out.config_yaml).unwrap(); + let c = cfg.providers.iter().find(|p| p.name == "chatgpt").unwrap(); + assert!(c.disabled); + assert_eq!(c.oauth.as_ref().unwrap().refresh, "rt-1"); + assert_eq!( + c.headers.get("ChatGPT-Account-Id").unwrap().value.raw(), + "acct-1" + ); + // 别的设备上:只有上游本身 + let other = mat(&pack("version: 1\n"), &t); + assert!(!other.config_yaml.contains("rt-1"), "{}", other.config_yaml); + assert!( + !other.config_yaml.contains("acct-1"), + "{}", + other.config_yaml + ); +} + +// ─────────────────────────────────────────────────────────── 插件 + +fn with_plugins(entries: &[(&str, &str, bool)]) -> Pack { + let mut text = format!( + "version: 1\nlisten:\n control:\n key: {KEY}\nclients:\n - name: default\n key: tw-a\nplugins:\n" + ); + let mut plugins = BTreeMap::new(); + for (id, source, enabled) in entries { + let sha = items::sha256_hex(source.as_bytes()); + text.push_str(&format!( + " - id: {id}\n file: plugins/{id}.js\n sha256: {sha}\n enabled: {enabled}\n" + )); + plugins.insert( + id.to_string(), + PluginFiles { + script: source.as_bytes().to_vec(), + approved: Some(source.as_bytes().to_vec()), + }, + ); + } + Pack { + plugins, + ..pack(&text) + } +} + +#[test] +fn a_plugin_splits_into_code_settings_and_switch() { + let p = with_plugins(&[ + ("note", "// data: {\"v\":1}\nmy code\n", true), + ( + "reply-language", + "// data: {\"lang\":\"zh\"}\nshipped code v1\n", + false, + ), + ]); + let s = snap(&p); + let note = &s.items[&id(ItemKind::Plugin, "note")]; + assert_eq!(note.units["script"], json!("// data: null\nmy code\n")); + assert_eq!(note.units["settings"], json!({"v": 1})); + assert_eq!(note.units["enabled"], json!(true)); + // 默认插件:脚本不比较,设置和开关照常 + let def = &s.items[&id(ItemKind::Plugin, "reply-language")]; + assert!(!def.units.contains_key("script")); + assert_eq!(def.units["settings"], json!({"lang": "zh"})); + assert_eq!( + s.items[&id(ItemKind::PluginOrder, "")].units["all"], + json!(["note", "reply-language"]) + ); +} + +#[test] +fn plugin_changes_land_on_the_files_and_the_entry() { + let codec = Fake::new(); + let p = with_plugins(&[ + ("note", "// data: {\"v\":1}\nmy code\n", true), + ( + "reply-language", + "// data: {\"lang\":\"zh\"}\nshipped code v1\n", + false, + ), + ]); + // 只改设置:本机的文件上改,照样批准着 + let mut t = snap(&p); + t.items + .get_mut(&id(ItemKind::Plugin, "note")) + .unwrap() + .units + .insert("settings".into(), json!({"v": 2})); + let out = materialize_with(&p, &t, &codec).unwrap(); + let f = &out.plugins["note"]; + assert_eq!(f.script, b"// data: {\"v\":2}\nmy code\n"); + assert_eq!(f.approved.as_deref(), Some(&f.script[..])); + let cfg = tw_config::try_parse(&out.config_yaml).unwrap(); + assert_eq!(cfg.plugins[0].sha256, items::sha256_hex(&f.script)); + // 默认插件在本机没有:用这一份 Core 自带的,设置照目标 + let bare = with_plugins(&[]); + let out = materialize_with(&bare, &snap(&p), &codec).unwrap(); + assert_eq!( + out.plugins["reply-language"].script, + b"// data: {\"lang\":\"zh\"}\nshipped code v1\n" + ); + assert_eq!(out.plugins["note"].script, b"// data: {\"v\":1}\nmy code\n"); + // 删掉一个 + let mut t = snap(&p); + t.items.remove(&id(ItemKind::Plugin, "note")); + t.items.insert( + id(ItemKind::PluginOrder, ""), + Item { + units: BTreeMap::from([("all".into(), json!(["reply-language"]))]), + ..Default::default() + }, + ); + let out = materialize_with(&p, &t, &codec).unwrap(); + assert!(!out.plugins.contains_key("note")); + assert!(!out.config_yaml.contains("id: note"), "{}", out.config_yaml); +} + +/// 改得了工具调用的插件:开着、而代码在本机没批准过时,落下去也不批准 +#[test] +fn a_steering_plugin_from_elsewhere_waits_for_approval_here() { + let codec = Fake::new(); + let src = "// data: {}\nsteer the tool calls\n"; + let theirs = with_plugins(&[("steerer", src, true)]); + let mut t = snap(&theirs); + // 带着原文件来(导入、同步都带着) + t.items + .get_mut(&id(ItemKind::Plugin, "steerer")) + .unwrap() + .files = theirs.plugins.get("steerer").cloned(); + let out = materialize_with(&with_plugins(&[]), &t, &codec).unwrap(); + let cfg = tw_config::try_parse(&out.config_yaml).unwrap(); + let e = &cfg.plugins[0]; + assert!(e.enabled); + assert_eq!(out.plugins["steerer"].script, src.as_bytes()); + assert_ne!( + e.sha256, + items::sha256_hex(src.as_bytes()), + "批准了别处来的代码" + ); + assert_eq!(out.plugins["steerer"].approved, None); + // 停用着来的照常批准:打开时才问 + let mut off = t.clone(); + off.items + .get_mut(&id(ItemKind::Plugin, "steerer")) + .unwrap() + .units + .insert("enabled".into(), json!(false)); + let out = materialize_with(&with_plugins(&[]), &off, &codec).unwrap(); + let cfg = tw_config::try_parse(&out.config_yaml).unwrap(); + assert_eq!(cfg.plugins[0].sha256, items::sha256_hex(src.as_bytes())); + // 本机停用着、批准过同一份代码,别处把它打开了:这里照样要点头 + let off_here = with_plugins(&[("steerer", src, false)]); + let mut t = snap(&off_here); + t.items + .get_mut(&id(ItemKind::Plugin, "steerer")) + .unwrap() + .units + .insert("enabled".into(), json!(true)); + let out = materialize_with(&off_here, &t, &codec).unwrap(); + let cfg = tw_config::try_parse(&out.config_yaml).unwrap(); + assert!(cfg.plugins[0].enabled); + assert_ne!( + cfg.plugins[0].sha256, + items::sha256_hex(&out.plugins["steerer"].script) + ); + // 读回来和目标一样:不会因为待批准就当成本机又改了一次 + assert_eq!( + snap(&out).items[&id(ItemKind::Plugin, "steerer")], + t.items[&id(ItemKind::Plugin, "steerer")] + ); + // 本机开着、批准过同一份代码:只改设置不用再批准 + let mine = with_plugins(&[("steerer", src, true)]); + let mut t = snap(&mine); + t.items + .get_mut(&id(ItemKind::Plugin, "steerer")) + .unwrap() + .units + .insert("settings".into(), json!({"x": 1})); + let out = materialize_with(&mine, &t, &codec).unwrap(); + let cfg = tw_config::try_parse(&out.config_yaml).unwrap(); + assert_eq!( + cfg.plugins[0].sha256, + items::sha256_hex(&out.plugins["steerer"].script) + ); +} + +/// 本机文件改了还没批准:比较按批准过的那一份,没批准的改动不往外带 +#[test] +fn an_unapproved_edit_is_neither_exported_nor_lost() { + let approved = "// data: {\"v\":1}\napproved code\n"; + let mut p = with_plugins(&[("note", approved, true)]); + p.plugins.get_mut("note").unwrap().script = + b"// data: {\"v\":1}\nedited, not approved\n".to_vec(); + let s = snap(&p); + assert_eq!( + s.items[&id(ItemKind::Plugin, "note")].units["script"], + json!("// data: null\napproved code\n") + ); + // 别处改了设置:本机那处没批准的改动留着,底稿和哈希换成新的 + let mut t = s.clone(); + t.items + .get_mut(&id(ItemKind::Plugin, "note")) + .unwrap() + .units + .insert("settings".into(), json!({"v": 2})); + let out = materialize_with(&p, &t, &Fake::new()).unwrap(); + let f = &out.plugins["note"]; + assert_eq!(f.script, b"// data: {\"v\":1}\nedited, not approved\n"); + assert_eq!( + f.approved.as_deref(), + Some(&b"// data: {\"v\":2}\napproved code\n"[..]) + ); +} + +#[test] +fn client_preferences_merge_field_by_field() { + let mut p = pack(&rich()); + p.client_prefs = Some(json!({"language": "zh", "menubar": {"show": "tokens", "rows": 2}})); + let s = snap(&p); + let prefs = &s.items[&id(ItemKind::ClientPrefs, "")]; + assert_eq!( + prefs.units.keys().collect::>(), + ["language", "menubar.rows", "menubar.show"] + ); + let mut t = s.clone(); + t.items + .get_mut(&id(ItemKind::ClientPrefs, "")) + .unwrap() + .units + .insert("menubar.show".into(), json!("speed")); + let out = mat(&p, &t); + assert_eq!( + out.client_prefs, + Some(json!({"language": "zh", "menubar": {"show": "speed", "rows": 2}})) + ); +} + +// ─────────────────────────────────────────────────────────── 改名 + +#[test] +fn renaming_follows_every_reference() { + let p = pack(&rich()); + type Check = fn(&Snapshot); + let cases: Vec<(ItemKind, &str, &str, Check)> = vec![ + (ItemKind::Provider, "relay", "relay (2)", |s| { + let g = &s.items[&ItemId::new(ItemKind::Group, "pool")].units["all"]; + assert_eq!(g["providers"], json!(["官方", "relay (2)"])); + let r = &s.items[&ItemId::new(ItemKind::Route, "长上下文")].units["all"]; + assert_eq!(r["rules"][0]["to"], json!("relay (2)")); + let o = &s.items[&ItemId::new(ItemKind::ProviderOrder, "")].units["all"]; + assert_eq!(o, &json!(["官方", "relay (2)", "chatgpt"])); + }), + (ItemKind::Proxy, "hk", "hk2", |s| { + let c = &s.items[&ItemId::new(ItemKind::Provider, "relay")].units["conn"]; + assert_eq!(c["proxy"], json!("hk2")); + }), + (ItemKind::PriceSheet, "中转", "中转 (2)", |s| { + let b = &s.items[&ItemId::new(ItemKind::Provider, "relay")].units["billing"]; + assert_eq!(b["pricing"], json!("中转 (2)")); + }), + (ItemKind::Key, "codex", "codex-2", |s| { + let r = &s.items[&ItemId::new(ItemKind::Route, "长上下文")].units["all"]; + assert_eq!(r["rules"][0]["when"]["client"], json!("codex-2")); + }), + (ItemKind::Key, "default", "main", |s| { + // 默认密钥原来是「叫 default 的那把」:改名之后要写明 + let g = &s.items[&ItemId::new(ItemKind::Global, "default_key")]; + assert_eq!(g.units["default_key"], json!("main")); + }), + (ItemKind::Alias, "fast", "quick", |s| { + let k = &s.items[&ItemId::new(ItemKind::Key, "codex")].units["all"]; + assert_eq!(k["allow"], json!(["quick"])); + }), + (ItemKind::Group, "pool", "pool2", |s| { + let r = &s.items[&ItemId::new(ItemKind::Route, "default")].units["all"]; + assert_eq!(r["rules"][0]["to"], json!("pool2")); + }), + (ItemKind::Route, "长上下文", "long", |s| { + let k = &s.items[&ItemId::new(ItemKind::Key, "codex")].units["all"]; + assert_eq!(k["route"], json!("long")); + let o = &s.items[&ItemId::new(ItemKind::RouteOrder, "")].units["all"]; + assert_eq!(o, &json!(["default", "long"])); + }), + (ItemKind::Route, "default", "main", |s| { + let g = &s.items[&ItemId::new(ItemKind::Global, "default_route")]; + assert_eq!(g.units["default_route"], json!("main")); + }), + (ItemKind::SecurityRule, "content/脏话", "粗话", |s| { + assert!( + s.items + .contains_key(&ItemId::new(ItemKind::SecurityRule, "content/粗话")) + ); + }), + ]; + for (kind, old, new, check) in cases { + let mut s = snap(&p); + rename(&mut s, &id(kind, old), new); + assert!(!s.items.contains_key(&id(kind, old)), "{old}"); + check(&s); + // 改了名的那一份落得回去、过得了校验 + let out = materialize_with(&p, &s, &Fake::new()).unwrap_or_else(|e| panic!("{old}: {e}")); + tw_config::try_parse(&out.config_yaml) + .unwrap_or_else(|e| panic!("{old} → {new}: {e}\n{}", out.config_yaml)); + assert_eq!(normalized(&snap(&out)), normalized(&s), "{old} → {new}"); + } + // 名字被占了、没有名字的项目:不动 + let mut s = snap(&p); + let before = s.clone(); + rename(&mut s, &id(ItemKind::Provider, "relay"), "官方"); + rename(&mut s, &id(ItemKind::Global, "failover"), "x"); + assert_eq!(s, before); + assert_eq!(free_name(&s, ItemKind::Provider, "relay"), "relay (2)"); + assert_eq!(free_name(&s, ItemKind::Provider, "new"), "new"); +} + +#[test] +fn retain_trims_the_orders_too() { + let mut s = snap(&pack(&rich())); + s.retain(&[id(ItemKind::Provider, "relay")].into_iter().collect()); + assert_eq!( + s.items.keys().map(|i| i.to_string()).collect::>(), + ["provider `relay`", "provider_order"] + ); + assert_eq!( + s.items[&id(ItemKind::ProviderOrder, "")].units["all"], + json!(["relay"]) + ); +} diff --git a/crates/tw-pack/src/model/write.rs b/crates/tw-pack/src/model/write.rs new file mode 100644 index 00000000..71f4ce39 --- /dev/null +++ b/crates/tw-pack/src/model/write.rs @@ -0,0 +1,799 @@ +//! 把目标状态落回配置文本:[`materialize`]。 +//! +//! # 两条路 +//! +//! 先**按项目改原文**(`tw_config::edit`):删掉目标里没有的,改掉变了的,加上新的,再排 +//! 顺序、改全局设置的字段。没变的项目一个字节都不动,旁边的注释也留着。改完读回来拆一遍, +//! 和目标对得上才算数。 +//! +//! 对不上(手写成了行内写法、锚点这类按项目改不动的)就**整份重写**:本机那几节原样留着, +//! 其余照目标生成。注释没了,但内容一定对。两条路都对不上就报错,什么都不写。 + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::Value as Json; +use serde_yaml_ng::{Mapping, Value as Yaml}; +use tw_config::edit::{self, Section}; +use tw_config::{Config, Plugin}; +use tw_yaml::Step; + +use super::items::{ + alias_models, approved_source, global_path, order_names, provider_mapping, rule_name, + sha256_hex, whole_mapping, +}; +use super::json::{key, to_yaml, unflatten}; +use super::{ + Item, ItemId, ItemKind, LOCAL_SECTIONS, ModelError, PluginCodec, Snapshot, codec, global, + normalized, parse, snapshot_with, unit, +}; +use crate::{Pack, PluginFiles}; + +const CLIENTS: Section = Section { + path: &["clients"], + what: "gateway key", + key: "name", +}; +const REDACT_RULES: Section = Section { + path: &["security", "redact", "custom"], + what: "custom rule", + key: "name", +}; +const TOOL_RULES: Section = Section { + path: &["security", "inspect_tools", "custom"], + what: "custom rule", + key: "name", +}; +const CONTENT_RULES: Section = Section { + path: &["security", "content", "custom"], + what: "custom rule", + key: "name", +}; + +/// 没有批准过的插件在配置里写的哈希:空文件的 SHA-256。哪个插件文件都对不上它,插件就 +/// 停在「文件变了、待批准」 +const NOT_APPROVED: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + +/// 以 `local` 为底,落成 `target` 那个样子:本机设置原样保留,其余换成 `target`;没变的 +/// 项目保留原文里的注释与顺序。用进程里装的插件拆法 +pub fn materialize(local: &Pack, target: &Snapshot) -> Result { + materialize_with(local, target, codec()) +} + +/// 同 [`materialize`],插件拆法由调用方给。 +/// +/// 插件: +/// +/// - 代码没变的(包括默认插件)在本机的文件上改数据,字节尽量不动;代码变了的、新来的用 +/// 目标里带着的原文件([`Item::files`]),没有就按单位拼出源码;默认插件在本机没有时 +/// 用这一份 Core 自带的那一份,也没有就不加 +/// - **改得了工具调用的插件,开着、而代码在本机没批准过(新来的、代码变了的、本机原来 +/// 停用着的)时不批准**:文件写下去,配置里的哈希留着本机原来批准的那一份(没有就是 +/// 一个谁都对不上的),插件停在「待批准」,要在本机点过头才跑 +/// - 别的照目标批准:哈希就是写下去的文件的 +pub fn materialize_with( + local: &Pack, + target: &Snapshot, + codec: &dyn PluginCodec, +) -> Result { + let cfg = parse(&local.config_yaml)?; + let current = snapshot_with(local, codec)?; + let plugins = plugin_outcomes(local, &cfg, ¤t, target, codec)?; + let want = complete_orders(normalized(target), &cfg, &plugins); + let prefs = target + .get(&ItemId::new(ItemKind::ClientPrefs, "")) + .map(|i| unflatten(&i.units)); + let files: BTreeMap = plugins + .iter() + .map(|(id, o)| (id.clone(), o.files.clone())) + .collect(); + let finish = |text: String| Pack { + manifest: local.manifest.clone(), + config_yaml: text, + plugins: files.clone(), + client_prefs: prefs.clone(), + }; + + let edited = by_edits(&local.config_yaml, &cfg, ¤t, target, &want, &plugins) + .map(&finish) + .ok() + .filter(|p| matches(p, &want, codec)); + if let Some(p) = edited { + return Ok(p); + } + let rebuilt = finish(rebuild(&local.config_yaml, &cfg, target, &want, &plugins)?); + if matches(&rebuilt, &want, codec) { + return Ok(rebuilt); + } + Err(ModelError::Verify { + detail: first_difference(&rebuilt, &want, codec), + }) +} + +/// 落下去的配置读回来拆一遍,和目标一样吗。**插件的脚本和设置不比**:待批准的插件读回来 +/// 按本机原来批准的那一份算,那正是要的样子;它们的文件由这里直接写 +fn matches(p: &Pack, want: &Snapshot, codec: &dyn PluginCodec) -> bool { + match snapshot_with(p, codec) { + Ok(got) => comparable(&normalized(&got)) == comparable(want), + Err(_) => false, + } +} + +fn comparable(s: &Snapshot) -> Snapshot { + let mut s = s.clone(); + for (id, item) in s.items.iter_mut() { + if id.kind == ItemKind::Plugin { + item.units.retain(|u, _| u == unit::ENABLED); + } + } + s +} + +fn first_difference(p: &Pack, want: &Snapshot, codec: &dyn PluginCodec) -> String { + let got = match snapshot_with(p, codec) { + Ok(s) => comparable(&normalized(&s)), + Err(e) => return e.to_string(), + }; + let want = comparable(want); + for (id, w) in &want.items { + match got.items.get(id) { + None => return format!("{id} is missing"), + Some(g) if g.units != w.units => return format!("{id} differs"), + _ => {} + } + } + match got.items.keys().find(|id| !want.items.contains_key(id)) { + Some(id) => format!("{id} is extra"), + None => "the order differs".into(), + } +} + +/// 落下去之后各种项目的先后:本机原来就有的按原来的先后、新的接在后面(按名字),再照 +/// 目标里的顺序项目排 —— 顺序项目里没列出来的接在列出来的后面。目标里的顺序项目缺了谁、 +/// 多了谁,落下去之后读回来都是这个样子,比较时按它 +fn complete_orders( + mut want: Snapshot, + cfg: &Config, + plugins: &BTreeMap, +) -> Snapshot { + for (kind, before) in [ + ( + ItemKind::Provider, + cfg.providers + .iter() + .map(|p| p.name.clone()) + .collect::>(), + ), + ( + ItemKind::Route, + cfg.routes.iter().map(|r| r.name.clone()).collect(), + ), + ( + ItemKind::Plugin, + cfg.plugins.iter().map(|p| p.id.clone()).collect(), + ), + ] { + let order_id = ItemId::new(kind.order().expect("these kinds have an order"), ""); + let present = |n: &String| { + want.items.contains_key(&ItemId::new(kind, n.clone())) + && (kind != ItemKind::Plugin || plugins.contains_key(n)) + }; + let mut all: Vec = before.into_iter().filter(|n| present(n)).collect(); + for (id, _) in want.of_kind(kind) { + if !all.contains(&id.name) && present(&id.name) { + all.push(id.name.clone()); + } + } + let listed = want + .get(&order_id) + .map(|o| order_names(&o.units)) + .unwrap_or_default(); + let fin = arrange(&all, &listed); + if fin.is_empty() { + want.items.remove(&order_id); + } else { + want.items.insert( + order_id, + Item { + units: BTreeMap::from([( + unit::ALL.to_string(), + Json::Array(fin.into_iter().map(Json::String).collect()), + )]), + ..Default::default() + }, + ); + } + } + want.items + .retain(|id, _| id.kind != ItemKind::Plugin || plugins.contains_key(&id.name)); + want +} + +// ─────────────────────────────────────────────────────────── 插件 + +struct PluginOut { + entry: Plugin, + files: PluginFiles, + /// 配置里那一条和本机的不一样(或者是新的) + changed: bool, +} + +fn plugin_outcomes( + local: &Pack, + cfg: &Config, + current: &Snapshot, + target: &Snapshot, + codec: &dyn PluginCodec, +) -> Result, ModelError> { + let mut out = BTreeMap::new(); + for (id, t) in target.of_kind(ItemKind::Plugin) { + let name = id.name.as_str(); + let le = cfg.plugins.iter().find(|p| p.id == name); + let lf = local.plugins.get(name); + let li = current.items.get(id); + if let (Some(le), Some(lf), Some(li)) = (le, lf, li) + && li.units == t.units + { + out.insert( + name.to_string(), + PluginOut { + entry: le.clone(), + files: lf.clone(), + changed: false, + }, + ); + continue; + } + let enabled = t + .units + .get(unit::ENABLED) + .and_then(Json::as_bool) + .unwrap_or(true); + let t_script = t.units.get(unit::SCRIPT); + let local_approved = match (le, lf) { + (Some(le), Some(lf)) => { + let a = approved_source(le, lf); + (sha256_hex(a) == le.sha256).then(|| a.to_vec()) + } + _ => None, + }; + let same_code = li.is_some_and(|li| li.units.get(unit::SCRIPT) == t_script) && lf.is_some(); + let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); + let base: Option = if same_code { + lf.map(|lf| text(le.map_or(&lf.script[..], |le| approved_source(le, lf)))) + } else if let Some(f) = t.files.as_ref().filter(|f| { + let src = text(&f.script); + let code = codec.split(&src).map_or(src, |(c, _)| c); + t_script.and_then(Json::as_str) == Some(code.as_str()) + }) { + Some(text(&f.script)) + } else if let Some(s) = t_script.and_then(Json::as_str) { + Some(s.to_string()) + } else if let (Some(le), Some(lf)) = (le, lf) { + // 默认插件:本机的那一份 + Some(text(approved_source(le, lf))) + } else { + codec.shipped(name) + }; + let Some(base) = base else { + // 默认插件,而这一份 Core 没有它:不加 + continue; + }; + let source = match t.units.get(unit::SETTINGS) { + Some(d) => codec.join(&base, d).ok_or_else(|| ModelError::Shape { + item: id.to_string(), + detail: "its settings do not fit its script".into(), + })?, + None => base, + }; + let approved_here = + le.is_some_and(|le| le.enabled) && same_code && local_approved.is_some(); + let gated = enabled && codec.needs_approval(&source) && !approved_here; + let pending_edit = match (le, lf) { + (Some(le), Some(lf)) => sha256_hex(&lf.script) != le.sha256, + _ => false, + }; + let (files, sha256) = if gated { + // 哈希留着本机原来批准的那一份(界面拿它和底稿比出改了什么);它恰好就是要写下去 + // 的这一份(本机停用着、批准过同一份代码)时也不能留:留着就等于替人点了头 + let sha = match le { + Some(le) if le.sha256 != sha256_hex(source.as_bytes()) => le.sha256.clone(), + _ => NOT_APPROVED.to_string(), + }; + ( + PluginFiles { + script: source.into_bytes(), + approved: local_approved.clone(), + }, + sha, + ) + } else if same_code && pending_edit { + // 本机有一处还没批准的改动:留着它,底稿和哈希换成新的 + let sha = sha256_hex(source.as_bytes()); + ( + PluginFiles { + script: lf.map(|f| f.script.clone()).unwrap_or_default(), + approved: Some(source.into_bytes()), + }, + sha, + ) + } else { + let sha = sha256_hex(source.as_bytes()); + let bytes = source.into_bytes(); + ( + PluginFiles { + script: bytes.clone(), + approved: Some(bytes), + }, + sha, + ) + }; + let entry = Plugin { + id: name.to_string(), + file: Plugin::file_for(name), + sha256, + enabled, + }; + let changed = le != Some(&entry); + out.insert( + name.to_string(), + PluginOut { + entry, + files, + changed, + }, + ); + } + Ok(out) +} + +// ─────────────────────────────────────────────────────────── 按项目改 + +fn section_of(id: &ItemId) -> Option<(Section, String)> { + let s = match id.kind { + ItemKind::Provider => edit::PROVIDERS, + ItemKind::Proxy => edit::PROXIES, + ItemKind::Key => CLIENTS, + ItemKind::Group => edit::GROUPS, + ItemKind::Route => edit::ROUTES, + ItemKind::PriceSheet => edit::PRICE_SHEETS, + ItemKind::Plugin => edit::PLUGINS, + ItemKind::SecurityRule => { + let (guard, rule) = rule_name(&id.name)?; + let s = match guard { + "redact" => REDACT_RULES, + "inspect_tools" => TOOL_RULES, + _ => CONTENT_RULES, + }; + return Some((s, rule.to_string())); + } + _ => return None, + }; + Some((s, id.name.clone())) +} + +/// 一项在配置里的样子(名字键在里面) +fn mapping_of( + id: &ItemId, + item: &Item, + cfg: &Config, + plugins: &BTreeMap, +) -> Result { + let m = match id.kind { + ItemKind::Provider => { + let local = cfg.providers.iter().find(|p| p.name == id.name); + provider_mapping(id, &item.units, local)?.1 + } + ItemKind::Proxy => whole_mapping::(id, &id.name, &item.units)?.1, + ItemKind::Key => whole_mapping::(id, &id.name, &item.units)?.1, + ItemKind::Group => whole_mapping::(id, &id.name, &item.units)?.1, + ItemKind::Route => whole_mapping::(id, &id.name, &item.units)?.1, + ItemKind::PriceSheet => whole_mapping::(id, &id.name, &item.units)?.1, + ItemKind::SecurityRule => { + let Some((guard, rule)) = rule_name(&id.name) else { + return Err(ModelError::Shape { + item: id.to_string(), + detail: "the name is not /".into(), + }); + }; + match guard { + "redact" => whole_mapping::(id, rule, &item.units)?.1, + "inspect_tools" => { + whole_mapping::(id, rule, &item.units)?.1 + } + _ => whole_mapping::(id, rule, &item.units)?.1, + } + } + ItemKind::Plugin => { + let Some(o) = plugins.get(&id.name) else { + return Err(ModelError::Shape { + item: id.to_string(), + detail: "there is no script for it".into(), + }); + }; + match serde_yaml_ng::to_value(&o.entry) { + Ok(Yaml::Mapping(m)) => m, + _ => { + return Err(ModelError::Shape { + item: id.to_string(), + detail: "it does not serialize to a mapping".into(), + }); + } + } + } + _ => { + return Err(ModelError::Shape { + item: id.to_string(), + detail: "it is not a list entry".into(), + }); + } + }; + Ok(m) +} + +fn by_edits( + text: &str, + cfg: &Config, + current: &Snapshot, + target: &Snapshot, + want: &Snapshot, + plugins: &BTreeMap, +) -> Result { + let mut text = text.to_string(); + let wanted = + |id: &ItemId| -> bool { id.kind != ItemKind::Plugin || plugins.contains_key(&id.name) }; + + // 删:先删引用别人的,再删被引用的(文本上无所谓,读起来顺) + for id in current.items.keys().rev() { + if !id.kind.is_named() || (target.items.contains_key(id) && wanted(id)) { + continue; + } + text = remove(&text, id)?; + } + // 改、加 + for (id, t) in &target.items { + if !id.kind.is_named() || !wanted(id) { + continue; + } + let existing = current.items.get(id); + let same = match id.kind { + ItemKind::Plugin => existing.is_some() && !plugins[&id.name].changed, + _ => existing.is_some_and(|c| c.units == t.units), + }; + if same { + continue; + } + text = upsert(&text, id, t, existing.is_some(), cfg, plugins)?; + } + // 顺序 + for (kind, section) in [ + (ItemKind::Provider, edit::PROVIDERS), + (ItemKind::Route, edit::ROUTES), + (ItemKind::Plugin, edit::PLUGINS), + ] { + let Some(order) = kind.order().and_then(|o| target.get(&ItemId::new(o, ""))) else { + continue; + }; + let doc = edit::parse(&text)?; + let now = names_in(&doc, section); + let desired = arrange(&now, &order_names(&order.units)); + if desired != now { + text = edit::reorder(&text, section, &desired)?; + } + } + // 全局设置:逐个字段 + for section in global::ALL { + let id = ItemId::new(ItemKind::Global, *section); + let empty = BTreeMap::new(); + let l = current.get(&id).map_or(&empty, |i| &i.units); + let t = want.get(&id).map_or(&empty, |i| &i.units); + if l == t { + continue; + } + let paths: BTreeSet<&String> = l.keys().chain(t.keys()).collect(); + for p in paths { + let tv = t.get(p); + if l.get(p) == tv { + continue; + } + let steps: Vec = global_path(p).iter().map(Step::key).collect(); + text = edit::set(&text, &steps, tv.map(to_yaml).as_ref())?; + } + } + Ok(text) +} + +fn remove(text: &str, id: &ItemId) -> Result { + if id.kind == ItemKind::Alias { + return Ok(edit::remove_alias(text, &id.name)?); + } + let Some((section, name)) = section_of(id) else { + return Ok(text.to_string()); + }; + Ok(edit::remove(text, section, &name)?) +} + +fn upsert( + text: &str, + id: &ItemId, + item: &Item, + exists: bool, + cfg: &Config, + plugins: &BTreeMap, +) -> Result { + if id.kind == ItemKind::Alias { + let alias = tw_config::Alias { + name: id.name.clone(), + models: alias_models(id, &item.units)?, + }; + let current = exists.then_some(id.name.as_str()); + return Ok(edit::upsert_alias(text, current, &alias)?); + } + let Some((section, name)) = section_of(id) else { + return Ok(text.to_string()); + }; + let m = mapping_of(id, item, cfg, plugins)?; + let current = exists.then_some(name.as_str()); + Ok(edit::upsert(text, section, current, &m)?) +} + +/// 一段列表里各项的名字,按写的顺序 +fn names_in(doc: &Yaml, section: Section) -> Vec { + let mut cur = doc; + for k in section.path { + match cur.get(*k) { + Some(v) => cur = v, + None => return Vec::new(), + } + } + cur.as_sequence() + .into_iter() + .flatten() + .filter_map(|it| { + it.get(section.key) + .and_then(Yaml::as_str) + .map(str::to_string) + }) + .collect() +} + +/// 按 `order` 排 `now`:`order` 里有的按它的先后排在前面,没有的按原来的先后接在后面 +fn arrange(now: &[String], order: &[String]) -> Vec { + let present: BTreeSet<&String> = now.iter().collect(); + let mut out: Vec = order + .iter() + .filter(|n| present.contains(n)) + .cloned() + .collect(); + let mut seen: BTreeSet = out.iter().cloned().collect(); + for n in now { + if seen.insert(n.clone()) { + out.push(n.clone()); + } + } + // 同一个名字在 order 里写了两次:只留第一次 + let mut once = BTreeSet::new(); + out.retain(|n| once.insert(n.clone())); + out +} + +// ─────────────────────────────────────────────────────────── 整份重写 + +fn rebuild( + text: &str, + cfg: &Config, + target: &Snapshot, + want: &Snapshot, + plugins: &BTreeMap, +) -> Result { + let doc: Yaml = serde_yaml_ng::from_str(text).unwrap_or(Yaml::Null); + let mut out = Mapping::new(); + out.insert( + key("version"), + doc.get("version") + .cloned() + .unwrap_or(Yaml::Number(tw_config::SCHEMA_VERSION.into())), + ); + let local = |k: &str| doc.get(k).cloned(); + + // 一种项目在目标里的名字:原来就有的按原来的先后,新的接在后面;有顺序项目的照它排 + let names = |kind: ItemKind, before: Vec| -> Vec { + let mut all: Vec = before + .into_iter() + .filter(|n| target.items.contains_key(&ItemId::new(kind, n.clone()))) + .collect(); + for (id, _) in target.of_kind(kind) { + if !all.contains(&id.name) { + all.push(id.name.clone()); + } + } + if kind == ItemKind::Plugin { + all.retain(|n| plugins.contains_key(n)); + } + match kind.order().and_then(|o| target.get(&ItemId::new(o, ""))) { + Some(o) => arrange(&all, &order_names(&o.units)), + None => all, + } + }; + let list = |kind: ItemKind, before: Vec| -> Result, ModelError> { + names(kind, before) + .into_iter() + .map(|n| { + let id = ItemId::new(kind, n); + let item = &target.items[&id]; + mapping_of(&id, item, cfg, plugins).map(Yaml::Mapping) + }) + .collect() + }; + + if let Some(v) = local("listen") { + out.insert(key("listen"), v); + } + let seq = |v: Vec| (!v.is_empty()).then_some(Yaml::Sequence(v)); + if let Some(v) = seq(list( + ItemKind::Key, + cfg.clients.iter().map(|c| c.name.clone()).collect(), + )?) { + out.insert(key("clients"), v); + } + if let Some(v) = seq(list( + ItemKind::Provider, + cfg.providers.iter().map(|p| p.name.clone()).collect(), + )?) { + out.insert(key("providers"), v); + } + if let Some(v) = seq(list( + ItemKind::Proxy, + cfg.proxies.iter().map(|p| p.name.clone()).collect(), + )?) { + out.insert(key("proxies"), v); + } + + // 全局设置:每一节按单位拼出来,读进类型核过 + let section = |name: &str| -> Result { + let mut v = Json::Object(Default::default()); + if let Some(item) = want.get(&ItemId::new(ItemKind::Global, name)) { + for (path, value) in &item.units { + let parts = global_path(path); + super::items::set_path(&mut v, &parts[1..], value.clone()); + } + } + super::items::section_normalized(name, &v).map_err(|detail| ModelError::Shape { + item: format!("global `{name}`"), + detail, + }) + }; + let mut pricing = section(global::PRICING)?; + let sheets = list( + ItemKind::PriceSheet, + cfg.pricing.sheets.iter().map(|s| s.name.clone()).collect(), + )?; + let mut pricing_yaml = match to_yaml(&pricing.take()) { + Yaml::Mapping(m) => m, + _ => Mapping::new(), + }; + if !sheets.is_empty() { + pricing_yaml.insert(key("sheets"), Yaml::Sequence(sheets)); + } + if !pricing_yaml.is_empty() { + out.insert(key("pricing"), Yaml::Mapping(pricing_yaml)); + } + let probes = to_yaml(§ion(global::CLIENT_PROBES)?); + if probes.as_mapping().is_some_and(|m| !m.is_empty()) { + out.insert(key("client_probes"), probes); + } + let mut security = match to_yaml(§ion(global::SECURITY)?) { + Yaml::Mapping(m) => m, + _ => Mapping::new(), + }; + for (guard, before) in [ + ( + "redact", + cfg.security + .redact + .custom + .iter() + .map(|r| r.name.clone()) + .collect::>(), + ), + ( + "inspect_tools", + cfg.security + .inspect_tools + .custom + .iter() + .map(|r| r.name.clone()) + .collect(), + ), + ( + "content", + cfg.security + .content + .custom + .iter() + .map(|r| r.name.clone()) + .collect(), + ), + ] { + let prefix = format!("{guard}/"); + let before = before.into_iter().map(|n| format!("{prefix}{n}")).collect(); + let own: Vec = names(ItemKind::SecurityRule, before) + .into_iter() + .filter(|n| n.starts_with(&prefix)) + .map(|n| { + let id = ItemId::new(ItemKind::SecurityRule, n); + mapping_of(&id, &target.items[&id], cfg, plugins).map(Yaml::Mapping) + }) + .collect::>()?; + if !own.is_empty() { + let entry = security + .entry(key(guard)) + .or_insert_with(|| Yaml::Mapping(Mapping::new())); + if let Yaml::Mapping(g) = entry { + g.insert(key("custom"), Yaml::Sequence(own)); + } + } + } + if !security.is_empty() { + out.insert(key("security"), Yaml::Mapping(security)); + } + if let Some(v) = local("retention") { + out.insert(key("retention"), v); + } + let failover = to_yaml(§ion(global::FAILOVER)?); + if failover.as_mapping().is_some_and(|m| !m.is_empty()) { + out.insert(key("failover"), failover); + } + // 别名表:名字 → 一个模型是字符串,几个是列表 + let mut aliases = Mapping::new(); + for n in names( + ItemKind::Alias, + cfg.aliases.iter().map(|a| a.name.clone()).collect(), + ) { + let id = ItemId::new(ItemKind::Alias, n.clone()); + let models = alias_models(&id, &target.items[&id].units)?; + let v = match models.as_slice() { + [one] => Yaml::String(one.clone()), + many => Yaml::Sequence(many.iter().cloned().map(Yaml::String).collect()), + }; + aliases.insert(key(&n), v); + } + if !aliases.is_empty() { + out.insert(key("aliases"), Yaml::Mapping(aliases)); + } + if let Some(v) = seq(list( + ItemKind::Group, + cfg.groups.iter().map(|g| g.name.clone()).collect(), + )?) { + out.insert(key("groups"), v); + } + if let Some(v) = seq(list( + ItemKind::Route, + cfg.routes.iter().map(|r| r.name.clone()).collect(), + )?) { + out.insert(key("routes"), v); + } + for name in [global::DEFAULT_ROUTE, global::DEFAULT_KEY] { + if let Some(v) = want + .get(&ItemId::new(ItemKind::Global, name)) + .and_then(|i| i.units.get(name)) + { + out.insert(key(name), to_yaml(v)); + } + } + if let Some(v) = seq(list( + ItemKind::Plugin, + cfg.plugins.iter().map(|p| p.id.clone()).collect(), + )?) { + out.insert(key("plugins"), v); + } + for k in LOCAL_SECTIONS { + if !out.contains_key(key(k)) + && let Some(v) = local(k) + { + out.insert(key(k), v); + } + } + serde_yaml_ng::to_string(&Yaml::Mapping(out)).map_err(|e| ModelError::Verify { + detail: e.to_string(), + }) +} diff --git a/crates/tw-pack/src/tests.rs b/crates/tw-pack/src/tests.rs new file mode 100644 index 00000000..d4e9e03b --- /dev/null +++ b/crates/tw-pack/src/tests.rs @@ -0,0 +1,334 @@ +//! 配置包的格式:写出去读得回来,读的时候不信任文件。 + +use std::io::Write; + +use super::*; + +fn fast() { + // 口令加密的工作量调低:测试不用每次等一秒 + TEST_WORK_FACTOR.store(10, std::sync::atomic::Ordering::Relaxed); +} + +fn sample() -> Pack { + let mut plugins = BTreeMap::new(); + plugins.insert( + "add-date".to_string(), + PluginFiles { + script: b"export const manifest = { name: \"x\", api: 1 };\n".to_vec(), + approved: Some(b"export const manifest = { name: \"x\", api: 1 };\n".to_vec()), + }, + ); + plugins.insert( + "only-script".to_string(), + PluginFiles { + script: b"// no approved copy\n".to_vec(), + approved: None, + }, + ); + Pack { + manifest: Manifest::new(PackKind::Full, PackOrigin::Export), + config_yaml: "version: 1\n# 注释\nproviders:\n - { name: a, base_url: https://a.example, key: sk-a }\nclients:\n - { name: default, key: tw-k }\n".into(), + plugins, + client_prefs: Some(serde_json::json!({"language": "zh", "menubar": {"show": "tokens"}})), + } +} + +#[test] +fn a_pack_reads_back_exactly_as_written_with_each_seal() { + fast(); + let pack = sample(); + let id = age::x25519::Identity::generate(); + let recipient = id.to_public(); + for (seal, unseal) in [ + (Seal::None, Unseal::None), + ( + Seal::Passphrase("correct horse"), + Unseal::Passphrase("correct horse"), + ), + (Seal::Recipient(&recipient), Unseal::Identity(&id)), + ] { + let encrypted = !matches!(seal, Seal::None); + let bytes = write(&pack, seal).unwrap(); + assert_eq!(is_encrypted(&bytes), encrypted); + let back = read(&bytes, unseal).unwrap(); + assert_eq!(back.config_yaml, pack.config_yaml); + assert_eq!(back.plugins, pack.plugins); + assert_eq!(back.client_prefs, pack.client_prefs); + assert_eq!(back.manifest.encrypted, encrypted); + assert_eq!(back.manifest.counts.providers, 1); + assert_eq!(back.manifest.counts.clients, 1); + assert_eq!(back.manifest.origin, PackOrigin::Export); + assert_eq!(back.manifest.core_version, CORE_VERSION); + } +} + +/// 内容一样,字节就一样(只差创建时间):备份去重、同步比较靠得住 +#[test] +fn the_same_content_writes_the_same_bytes() { + let mut a = sample(); + a.manifest.created_at_ms = 1; + let b = a.clone(); + assert_eq!( + write(&a, Seal::None).unwrap(), + write(&b, Seal::None).unwrap() + ); +} + +#[test] +fn opening_an_encrypted_pack_needs_the_right_secret() { + fast(); + let pack = sample(); + let by_pass = write(&pack, Seal::Passphrase("right one")).unwrap(); + let id = age::x25519::Identity::generate(); + let by_key = write(&pack, Seal::Recipient(&id.to_public())).unwrap(); + let other = age::x25519::Identity::generate(); + let cases: Vec<(&[u8], Unseal, PackError)> = vec![ + (&by_pass, Unseal::None, PackError::NeedPassphrase), + ( + &by_pass, + Unseal::Passphrase("wrong one"), + PackError::WrongPassphrase, + ), + (&by_pass, Unseal::Identity(&id), PackError::NeedPassphrase), + (&by_key, Unseal::None, PackError::NeedKey), + (&by_key, Unseal::Passphrase("right one"), PackError::NeedKey), + (&by_key, Unseal::Identity(&other), PackError::WrongKey), + ]; + for (bytes, unseal, want) in cases { + assert_eq!(read(bytes, unseal).unwrap_err(), want); + } +} + +/// 手工做一个 ZIP:测「读的时候不信任文件」 +fn zip_of(entries: &[(&str, &[u8])]) -> Vec { + let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, bytes) in entries { + z.start_file(*name, opts).unwrap(); + z.write_all(bytes).unwrap(); + } + z.finish().unwrap().into_inner() +} + +fn manifest_json(format: u32) -> Vec { + let mut m = Manifest::new(PackKind::Full, PackOrigin::Export); + m.format = format; + serde_json::to_vec(&m).unwrap() +} + +#[test] +fn a_pack_with_anything_unexpected_inside_is_refused_whole() { + let m = manifest_json(FORMAT); + let cfg: &[u8] = b"version: 1\n"; + for (bad, why) in [ + ("../config.yaml", "climbs out"), + ("/etc/passwd", "absolute"), + ("plugins/../../x.js", "climbs out through plugins"), + ("plugins/Bad_Id.js", "an id that is not one"), + ("plugins/a.txt", "not a script"), + ( + "plugins/.approved/../a.js", + "climbs out of the approved copies", + ), + ("README.md", "a file a pack does not have"), + ("plugins/sub/a.js", "a nested directory"), + ] { + let bytes = zip_of(&[("manifest.json", &m), ("config.yaml", cfg), (bad, b"x")]); + match read(&bytes, Unseal::None) { + Err(PackError::BadEntry { name }) => assert_eq!(name, bad, "{why}"), + other => panic!("{why}: {other:?}"), + } + } + // 只有底稿没有脚本 + let bytes = zip_of(&[ + ("manifest.json", &m), + ("config.yaml", cfg), + ("plugins/.approved/a.js", b"x"), + ]); + assert!(matches!( + read(&bytes, Unseal::None), + Err(PackError::BadEntry { .. }) + )); + // 目录条目无害 + let bytes = zip_of(&[ + ("manifest.json", &m), + ("config.yaml", cfg), + ("plugins/", b""), + ("plugins/.approved/", b""), + ("plugins/a.js", b"x"), + ]); + assert_eq!(read(&bytes, Unseal::None).unwrap().plugins.len(), 1); +} + +#[test] +fn a_pack_missing_its_manifest_or_config_says_which() { + let m = manifest_json(FORMAT); + for (entries, missing) in [ + (vec![("config.yaml", &b"version: 1\n"[..])], "manifest.json"), + (vec![("manifest.json", &m[..])], "config.yaml"), + ] { + let e = read(&zip_of(&entries), Unseal::None).unwrap_err(); + assert_eq!( + e, + PackError::MissingEntry { + name: missing.into() + } + ); + assert_eq!(e.msg().code, "pack.missing_entry"); + } +} + +#[test] +fn a_newer_format_is_too_new_and_not_corrupt() { + let m = manifest_json(FORMAT + 1); + let bytes = zip_of(&[("manifest.json", &m), ("config.yaml", b"version: 1\n")]); + match read(&bytes, Unseal::None) { + Err(PackError::TooNew { + format, + core_version, + }) => { + assert_eq!(format, FORMAT + 1); + assert_eq!(core_version, CORE_VERSION); + } + other => panic!("{other:?}"), + } + // 新的格式里清单多了不认识的字段,照样先说太新 + let raw = serde_json::json!({"format": FORMAT + 1, "whatever": [1, 2]}); + let bytes = zip_of(&[ + ("manifest.json", raw.to_string().as_bytes()), + ("config.yaml", b"version: 1\n"), + ]); + assert!(matches!( + read(&bytes, Unseal::None), + Err(PackError::TooNew { .. }) + )); + // 同一个格式里多出来的字段不碍事:新一点的 Core 写的、格式没变的包读得进来 + let mut raw: serde_json::Value = serde_json::from_slice(&manifest_json(FORMAT)).unwrap(); + raw["something_new"] = serde_json::json!(true); + raw["origin"] = serde_json::json!("a_new_origin"); + let bytes = zip_of(&[ + ("manifest.json", raw.to_string().as_bytes()), + ("config.yaml", b"version: 1\n"), + ]); + let p = read(&bytes, Unseal::None).unwrap(); + assert_eq!(p.manifest.origin, PackOrigin::Other); +} + +#[test] +fn garbage_is_corrupt_and_says_so() { + for bytes in [&b"not a zip at all"[..], b"PK\x03\x04broken", b""] { + let e = read(bytes, Unseal::None).unwrap_err(); + assert!(matches!(e, PackError::Corrupt { .. }), "{e:?}"); + assert_eq!(e.msg().code, "pack.corrupt"); + } + let m = manifest_json(FORMAT); + let bytes = zip_of(&[("manifest.json", &m), ("config.yaml", &[0xff, 0xfe])]); + assert!(matches!( + read(&bytes, Unseal::None), + Err(PackError::Corrupt { .. }) + )); + let bytes = zip_of(&[ + ("manifest.json", b"{not json"), + ("config.yaml", b"version: 1\n"), + ]); + assert!(matches!( + read(&bytes, Unseal::None), + Err(PackError::Corrupt { .. }) + )); +} + +/// 解压之后的大小按真读到的算:一个压得很小、解开很大的包挡在门口 +#[test] +fn a_pack_that_unpacks_to_more_than_the_limit_is_refused() { + let m = manifest_json(FORMAT); + let big = vec![b'a'; MAX_BYTES + 1]; + let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated) + .large_file(true); + z.start_file("manifest.json", opts).unwrap(); + z.write_all(&m).unwrap(); + z.start_file("config.yaml", opts).unwrap(); + z.write_all(&big).unwrap(); + let bytes = z.finish().unwrap().into_inner(); + assert!(bytes.len() < MAX_BYTES, "the compressed file is small"); + assert_eq!( + read(&bytes, Unseal::None).unwrap_err(), + PackError::TooLarge { limit: MAX_BYTES } + ); + // 本身就太大的文件不打开 + assert_eq!( + read(&vec![0u8; MAX_BYTES + 1], Unseal::None).unwrap_err(), + PackError::TooLarge { limit: MAX_BYTES } + ); + // 写的时候也挡 + let mut p = sample(); + p.config_yaml = "a".repeat(MAX_BYTES * 2); + // 压得很小的内容照样按解压后的大小算:写得出去就得读得回来 + assert_eq!( + write(&p, Seal::None).unwrap_err(), + PackError::TooLarge { limit: MAX_BYTES } + ); +} + +#[test] +fn every_error_speaks_with_its_own_code() { + let all = [ + (PackError::NeedPassphrase, "pack.need_passphrase"), + (PackError::WrongPassphrase, "pack.wrong_passphrase"), + (PackError::NeedKey, "pack.need_key"), + (PackError::WrongKey, "pack.wrong_key"), + ( + PackError::TooNew { + format: 2, + core_version: "9.0.0".into(), + }, + "pack.too_new", + ), + (PackError::Corrupt { detail: "x".into() }, "pack.corrupt"), + (PackError::BadEntry { name: "x".into() }, "pack.bad_entry"), + ( + PackError::MissingEntry { name: "x".into() }, + "pack.missing_entry", + ), + (PackError::TooLarge { limit: MAX_BYTES }, "pack.too_large"), + ]; + for (e, code) in all { + assert_eq!(e.msg().code, code); + assert_eq!(e.to_string(), e.msg().text); + } + assert_eq!( + PackError::TooLarge { limit: MAX_BYTES }.msg().arg("limit"), + "16" + ); +} + +#[test] +fn versions_compare_as_numbers() { + assert!(!newer_than_us(CORE_VERSION)); + assert!(newer_than_us("999.0.0")); + assert!(!newer_than_us("0.0.1")); + assert!(!newer_than_us("not a version")); + assert_eq!(parse_version("0.77.0-rc.1"), Some((0, 77, 0))); + assert_eq!(parse_version("1.2"), Some((1, 2, 0))); +} + +#[test] +fn origins_keep_their_words() { + for o in [ + PackOrigin::Export, + PackOrigin::Share, + PackOrigin::Ui, + PackOrigin::Cli, + PackOrigin::External, + PackOrigin::Defaults, + PackOrigin::Sync, + PackOrigin::Import, + PackOrigin::Restore, + PackOrigin::Repair, + ] { + assert_eq!(serde_json::to_value(o).unwrap(), o.slug()); + assert_eq!(PackOrigin::from_slug(o.slug()), o); + } + assert_eq!(PackOrigin::from_slug("nope"), PackOrigin::Other); +} From 037169e8bc37a791f090a2725ff6367c863d62ba Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:09:39 +0800 Subject: [PATCH 2/2] tw-pack: zip 9 (RUSTSEC-2026-0367/0368/0369); a clippy fix for Rust 1.99 The advisories are about extracting archives to disk, which this crate never does, but the patched release is the one to depend on. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 17 +++++++++++++++-- Cargo.toml | 2 +- crates/tw-pack/src/lib.rs | 2 +- crates/tw-pack/src/model/write.rs | 3 ++- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 236aa92c..03cbac05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2098,6 +2098,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -4890,14 +4902,15 @@ dependencies = [ [[package]] name = "zip" -version = "8.6.0" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ "crc32fast", "flate2", "indexmap", "memchr", + "nix", "typed-path", ] diff --git a/Cargo.toml b/Cargo.toml index 20beb178..a2d085af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -169,7 +169,7 @@ clap = { version = "4", features = ["derive"] } # SSH 密钥、插件、命令行那几样 age = { version = "0.11", default-features = false } # 配置包本身是 ZIP。只要 deflate(走已经在依赖树里的 flate2),不要别的压缩算法和加密 -zip = { version = "8", default-features = false, features = ["deflate-flate2"] } +zip = { version = "9", default-features = false, features = ["deflate-flate2"] } # 控制面契约导出成 TypeScript(tw-api 的 `ts` feature)。**不开任何 serde 以外的 # 类型实现**:契约里只有 std 和 serde 的类型 ts-rs = { version = "12", default-features = false, features = ["serde-compat"] } diff --git a/crates/tw-pack/src/lib.rs b/crates/tw-pack/src/lib.rs index d4cba732..99c1e4c6 100644 --- a/crates/tw-pack/src/lib.rs +++ b/crates/tw-pack/src/lib.rs @@ -565,7 +565,7 @@ fn unzip(bytes: &[u8]) -> Result { let mut budget = MAX_BYTES; for i in 0..z.len() { let mut f = z.by_index(i).map_err(corrupt)?; - let name = f.name().to_string(); + let name = f.name().map_err(corrupt)?.to_string(); let Some(kind) = entry_of(&name) else { return Err(PackError::BadEntry { name }); }; diff --git a/crates/tw-pack/src/model/write.rs b/crates/tw-pack/src/model/write.rs index 71f4ce39..ff3355bc 100644 --- a/crates/tw-pack/src/model/write.rs +++ b/crates/tw-pack/src/model/write.rs @@ -86,6 +86,7 @@ pub fn materialize_with( .iter() .map(|(id, o)| (id.clone(), o.files.clone())) .collect(); + let (files, prefs) = (&files, &prefs); let finish = |text: String| Pack { manifest: local.manifest.clone(), config_yaml: text, @@ -94,7 +95,7 @@ pub fn materialize_with( }; let edited = by_edits(&local.config_yaml, &cfg, ¤t, target, &want, &plugins) - .map(&finish) + .map(finish) .ok() .filter(|p| matches(p, &want, codec)); if let Some(p) = edited {