diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index d101da0..c8f974a 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -23,7 +23,8 @@ "ghcr.io/devcontainers/features/rust:1": { "version": "1.93.1", "profile": "minimal", - "components": "rustfmt,clippy" + "components": "rustfmt,clippy", + "targets": "wasm32-unknown-unknown" }, "ghcr.io/devcontainers/features/java:1": { "version": "17" }, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 056e048..8f9502d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,91 +5,29 @@ on: permissions: contents: read jobs: - native: - name: Native / ${{ matrix.platform }} - strategy: - fail-fast: false - matrix: - include: - - platform: linux-x64 - node-arch: x64 - runner: ubuntu-24.04 - target: x86_64-unknown-linux-gnu - - platform: linux-arm64 - node-arch: arm64 - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-gnu - - platform: darwin-arm64 - node-arch: arm64 - runner: macos-latest - target: aarch64-apple-darwin - - platform: win32-x64 - node-arch: x64 - runner: windows-latest - target: x86_64-pc-windows-msvc - runs-on: ${{ matrix.runner }} + build: + name: Build and test + runs-on: ubuntu-24.04 timeout-minutes: 30 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 26 - architecture: ${{ matrix.node-arch }} cache: npm - - name: Check the Node architecture - env: - NEO_PLATFORM: ${{ matrix.platform }} - run: node -e "if (process.platform + '-' + process.arch !== process.env.NEO_PLATFORM) process.exit(1)" - - run: rustup toolchain install 1.93.1 --profile minimal --component rustfmt --component clippy --target ${{ matrix.target }} - - uses: ilammy/msvc-dev-cmd@v1 - if: runner.os == 'Windows' + - run: rustup toolchain install 1.93.1 --profile minimal --component rustfmt --component clippy --target wasm32-unknown-unknown + # The command-line tool must match the wasm-bindgen crate version in wasm/Cargo.lock. + - uses: taiki-e/install-action@v2 with: - arch: amd64 - - name: Select Perl for vendored OpenSSL - if: runner.os == 'Windows' - shell: pwsh - run: | - $perlDir = 'C:\Strawberry\perl\bin' - if (-not (Test-Path "$perlDir\perl.exe")) { - choco install strawberryperl --no-progress -y - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - } - $perlDir | Out-File -FilePath $env:GITHUB_PATH -Append - - run: cargo fmt --check --manifest-path native/Cargo.toml - - run: cargo clippy --locked --all-targets --manifest-path native/Cargo.toml --target ${{ matrix.target }} -- -D warnings - - run: cargo test --locked --manifest-path native/Cargo.toml --target ${{ matrix.target }} + tool: wasm-bindgen@0.2.130 + - run: cargo fmt --check --manifest-path wasm/Cargo.toml + - run: cargo clippy --locked --all-targets --manifest-path wasm/Cargo.toml -- -D warnings + - run: cargo clippy --locked --manifest-path wasm/Cargo.toml --target wasm32-unknown-unknown -- -D warnings + - run: cargo test --locked --manifest-path wasm/Cargo.toml - run: npm ci --ignore-scripts - - run: npm run build:native + - run: npm run build:wasm - run: npm test - - run: npm run test:package - - uses: actions/upload-artifact@v4 - with: - name: neo-native-${{ matrix.platform }} - path: native/${{ matrix.platform }}/ - if-no-files-found: error - - package: - name: Assemble all-platform npm tarball - needs: native - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 26 - cache: npm - - uses: actions/download-artifact@v4 - with: - pattern: neo-native-* - path: native - - name: Stage each native build - run: | - for addon in native/neo-native-*; do - platform=${addon#native/neo-native-} - mv "$addon" "native/$platform" - done - - run: npm ci --ignore-scripts - - run: npm run build + # Installs the tarball in a fresh project, runs the package tests and keeps the tarball. - run: npm run test:package -- artifacts - uses: actions/upload-artifact@v4 with: @@ -99,7 +37,7 @@ jobs: publish: name: Publish to npm - needs: package + needs: build if: startsWith(github.ref, 'refs/tags/v') runs-on: ubuntu-24.04 environment: npm diff --git a/.gitignore b/.gitignore index 60b2908..362fa6d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,7 @@ node_modules/ dist/ -native/target/ -native/**/*.node +wasm/target/ +wasm/pkg/ *.tgz *.memory-card.json .env* -native/**/THIRD-PARTY.txt diff --git a/README.md b/README.md index 7ab71f4..6fae8e7 100644 --- a/README.md +++ b/README.md @@ -8,28 +8,22 @@ The 30-second live terminal demo shows QR login and the standalone TypeScript ex https://github.com/user-attachments/assets/e7e40c19-ad49-4061-be53-cef1e1c4c978 -Neo builds native addons for Linux x64 and ARM64, macOS on Apple Silicon, and Windows x64. CI tests an npm install on each target and assembles one tarball with all four addons. The prebuilt Linux addons require glibc 2.38 or newer. Neo loads the addon for the architecture of the running Node process. Use ARM64 Node.js on macOS. +Neo's protocol session is compiled to WebAssembly, so one package runs wherever Node.js 26 runs, with no native addon and nothing to compile on install. Node opens the TCP connections to WeChat's servers. CI builds it on Linux, installs the package in a fresh project and runs its tests there. -On Windows 11 on ARM, install **x64 Node.js** to use the x64 addon under Windows emulation. Run `node -p process.arch` to check that it prints `x64`. [Microsoft's emulation documentation](https://learn.microsoft.com/en-us/windows/arm/apps-on-arm-x86-emulation) - -To build from source, use Node.js 26 and Rust 1.93.1 with the matching Rust target. - -| Platform | Build prerequisites | -| --- | --- | -| Linux | C compiler, Make, Perl | -| macOS on Apple Silicon | Xcode Command Line Tools, Make, Perl | -| Windows x64 | MSVC x64 C++ tools, Windows SDK, Perl | +To build from source, use Node.js 26, Rust 1.93.1 with the `wasm32-unknown-unknown` target, and the `wasm-bindgen` command-line tool at the version in `wasm/Cargo.lock`. No C compiler or Perl is needed. ```sh +rustup target add wasm32-unknown-unknown +cargo install --locked wasm-bindgen-cli --version 0.2.130 npm ci -npm run build:native +npm run build:wasm npm run build node examples/ding-dong-bot.ts ``` Scan the terminal QR and confirm the login on your phone. The example prints the account's nickname. After `Ready` appears, send `ding` from another WeChat account, directly or in a group that includes this account. The example replies with `dong` in the same chat and prints the received message and reply. Signing the device out from the phone, or calling `puppet.logout()`, emits `logout` with the reason. Stop with Ctrl+C. Starting it again displays a new QR. -Node runs the TypeScript example directly. The commands above build the package and native addon from source. To use a prebuilt tarball in another project, install the tarball and copy its `examples/ding-dong-bot.ts` into that project before running it. +Node runs the TypeScript example directly. The commands above build the package and its WebAssembly session from source. To use a prebuilt tarball in another project, install the tarball and copy its `examples/ding-dong-bot.ts` into that project before running it. Run `npm test` for type checking and the offline tests, and `npm run test:package` to check a clean tarball installation. @@ -38,16 +32,16 @@ Run `npm test` for type checking and the offline tests, and `npm run test:packag CI publishes to npm when a `v` tag on `main` is pushed and every platform build and package test passes. The tag must match the `package.json` version. An odd minor version, such as 0.1.x, publishes on the `next` dist-tag; an even minor version publishes on `latest`, following the [Wechaty versioning conventions](https://github.com/wechaty/wechaty/issues/905). The tarball carries npm provenance from this workflow, which publishes through npm trusted publishing (OIDC) with no npm token. ```sh -git tag v0.1.2 -git push origin v0.1.2 +git tag v0.1.3 +git push origin v0.1.3 ``` ### Development container A dev container is a reproducible development workspace described in the repository. VS Code's Dev Containers extension can open the project inside that environment so contributors use the same OS and toolchain without installing Node.js or Rust on the host. -The configuration in [`.devcontainer/devcontainer.json`](.devcontainer/devcontainer.json) is based on the [Ship.Fail devcontainer template](https://github.com/ShipFail/devcontainer). It uses Ubuntu 24.04, Node.js 26, Rust 1.93.1 with `rustfmt` and `clippy`, and the C compiler, Make, and Perl needed for the native addon. It runs `npm ci` after container creation. It also retains the template's supporting CLI tools and mounts host Claude, Codex, Gemini, and Git configuration into the container; the GitHub CLI helper can use the host Git credential helper. Only use these host mounts when you trust the repository and its development tooling. +The configuration in [`.devcontainer/devcontainer.json`](.devcontainer/devcontainer.json) is based on the [Ship.Fail devcontainer template](https://github.com/ShipFail/devcontainer). It uses Ubuntu 24.04, Node.js 26, and Rust 1.93.1 with `rustfmt`, `clippy` and the `wasm32-unknown-unknown` target. Install `wasm-bindgen-cli` as shown above before `npm run build:wasm`. It runs `npm ci` after container creation. It also retains the template's supporting CLI tools and mounts host Claude, Codex, Gemini, and Git configuration into the container; the GitHub CLI helper can use the host Git credential helper. Only use these host mounts when you trust the repository and its development tooling. Windows contributors must use WSL to open the repository and run the dev container; native Windows host initialization is unsupported. Install the VS Code Dev Containers extension, then run **Dev Containers: Reopen in Container** from the Command Palette. -For live acceptance, use an isolated test account and a confirmed peer. The example replies to direct `ding` messages, including messages received during initial sync. Verify `dong` on the peer's device. Real-account testing has covered Linux x64. CI on the other targets covers addon loading, npm installation, and scripted Puppet behavior. +For live acceptance, use an isolated test account and a confirmed peer. The example replies to direct `ding` messages, including messages received during initial sync. Verify `dong` on the peer's device. Real-account testing has covered Linux x64. CI covers loading the WebAssembly session, npm installation, and scripted Puppet behavior. diff --git a/docs/v1-spec.md b/docs/v1-spec.md index 8b4a8ff..0f47ae3 100644 --- a/docs/v1-spec.md +++ b/docs/v1-spec.md @@ -4,11 +4,11 @@ Puppet Neo is a local WeChat protocol Puppet for Wechaty. Its long-term goal is ## First acceptance gate -Use an isolated Linux x64 test account and a confirmed separate peer. Build the addon and package, then run the repository example. +Use an isolated test account and a confirmed separate peer. Build the WebAssembly session and package, then run the repository example. ```sh npm ci -npm run build:native +npm run build:wasm npm run build node examples/ding-dong-bot.ts ``` @@ -28,16 +28,17 @@ The example listens for Puppet events, retrieves messages with `messagePayload() ```text ding-dong-bot.ts -> PuppetNeo (TypeScript, Puppet events and payload lookup) - -> NeoSession (.node, Rust account credentials and protocol operations) - -> wechat-protocol = 2.2.0 (published Cargo source) + -> NeoSession (WebAssembly, Rust account credentials and protocol operations) + -> wechat-protocol = 3.8.0 (published Cargo source, pure-Rust crypto) + -> NeoHost (Node.js TCP connections and clocks) -> WeChat servers ``` -Neo builds the addon from pinned crate sources. Cargo.lock and package-lock.json pin build inputs. Native CI builds and tests Linux x64 and ARM64 with glibc, macOS ARM64 on `macos-latest`, and Windows x64 on `windows-latest`. The combined npm tarball contains all four native builds and selects one using Node's platform and architecture. The CI-built Linux addons require glibc 2.38 or newer. +Neo builds the WebAssembly session from pinned crate sources with the protocol's pure-Rust crypto backend, so no OpenSSL or C toolchain is involved. Cargo.lock and package-lock.json pin build inputs, and the `wasm-bindgen` tool must match the crate version in Cargo.lock. CI builds the session on Linux, installs the tarball in a fresh project and runs the package tests there; the WebAssembly file and the Node APIs Neo uses behave the same on every platform. The npm tarball contains one WebAssembly file for every platform. -Blocking native calls run off the Node event loop, and a Rust lock serializes session access. TypeScript schedules login polling, sync and heartbeat, then maps incoming text to Puppet payloads and events. After authentication, Neo opens the account's incoming connection, drains initial sync, and requests NewSync when that connection or a heartbeat signals message work. +Session calls are asynchronous and run on the Node event loop. The WebAssembly session asks Node for TCP connections, reads, writes and the time, and an async lock serializes session access. TypeScript schedules login polling, sync and heartbeat, then maps incoming text to Puppet payloads and events. After authentication, Neo opens the account's incoming connection, drains initial sync, and requests NewSync when that connection or a heartbeat signals message work. -For protocol contributors, follow `messageSendText()` in [the Puppet](../src/puppet-neo.ts) into the [native session](../native/src/lib.rs), then see `AccountRequest::send_text` and `wire::text_send_request` in the [published Rust source](https://docs.rs/crate/wechat-protocol/2.2.0/source/src/). After login, the session moves the accepted credentials into one `NativeClient` account owner; the push connection and sends share it. Incoming text follows the reverse direction through NewSync and AddMsg decoding. +For protocol contributors, follow `messageSendText()` in [the Puppet](../src/puppet-neo.ts) into the [WebAssembly session](../wasm/src/lib.rs), then see `NativeClient::send_text` and `wire::text_send_request` in the [published Rust source](https://docs.rs/crate/wechat-protocol/3.8.0/source/src/). After login, the session moves the accepted credentials into one `NativeClient` account owner; the push connection and sends share it. Incoming text follows the reverse direction through NewSync and AddMsg decoding. ## State and errors @@ -68,7 +69,7 @@ Each session emits `logout` once: | WeChat rejects the session (`-13`) and also rejects one automatic renewal, for example after the device is signed out from the phone | `WeChat ended the session` | | Any other failure after login stops the session loop. An `error` event comes first | `Neo session failed` | -Signing out from the phone can close the socket before WeChat returns any code. So if the notification socket closes, or a sync or heartbeat fails without a service code, Neo reconnects once and repeats the read, and WeChat's answer decides whether the session is still valid. Neo uses the crate's typed errors for these decisions, never the error text. Sends are never repeated after a renewal. After a logout the puppet stays started; stop and start it to log in with a new QR. The base Puppet clears `currentUserId` one event-loop turn after emitting `logout`, so listeners can still read it. +Signing out from the phone can close the socket before WeChat returns any code. So if the notification socket closes, or a sync or heartbeat fails without a service code, Neo reconnects once and repeats the read, and WeChat's answer decides whether the session is still valid. Neo uses the crate's typed errors for these decisions, never the error text. Sends are never repeated after a renewal. After a logout the puppet stays started; stop and start it to log in with a new QR. The base Puppet clears `currentUserId` on the next timer tick after emitting `logout`, so listeners can still read it. WebAssembly cannot accept incoming connections, so a login that WeChat routes through its local-network check fails instead of completing; scan the QR again. ## Validation and release gates @@ -78,8 +79,8 @@ Signing out from the phone can close the socket before WeChat returns any code. | Puppet API | Scripted session drives QR login, text payload lookup, reply, clean stop and a fresh login | | Login and logout | Login after the profile, `ready` after the initial sync, nickname and fallback names, and one logout for stop, `logout()`, a session ended by WeChat during heartbeat or sync, and an unexpected failure | | Example | The actual TypeScript example runs against a scripted session and replies through PuppetNeo, directly and in a group | -| Native boundary | Load the addon without a storage key and reject unauthenticated operations | -| Package | Install a tarball in a fresh project and run the Puppet, native and example tests | +| WebAssembly boundary | Load the WebAssembly session and reject unauthenticated operations | +| Package | Install a tarball in a fresh project and run the Puppet, session and example tests | | Live acceptance | Fresh QR login showing the nickname, Ding Dong directly and in a group with an isolated test account, `logout` after signing out from the phone, then repeat after restarting | -Start with an npm development release on `next` after acceptance. Follow Wechaty's odd-minor development and even-minor stable convention. Use the combined tarball after its four native package checks pass and report live acceptance separately. Review the repository, installed example and release workflow with the Wechaty maintainers before expanding scope or promoting a stable release. Automatic publication follows that review. +Start with an npm development release on `next` after acceptance. Follow Wechaty's odd-minor development and even-minor stable convention. Use the tarball after its package checks pass and report live acceptance separately. Review the repository, installed example and release workflow with the Wechaty maintainers before expanding scope or promoting a stable release. Automatic publication follows that review. diff --git a/native/Cargo.toml b/native/Cargo.toml deleted file mode 100644 index ba82893..0000000 --- a/native/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "puppet-neo-native" -version = "0.1.0" -edition = "2021" -rust-version = "1.93.1" -publish = false - -[lib] -crate-type = ["cdylib"] - -[dependencies] -anyhow = "1" -base64 = "0.22" -napi = { version = "3", features = ["napi8", "serde-json"] } -napi-derive = "3" -openssl = { version = "0.10", features = ["vendored"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -wechat-protocol = "=2.2.0" - -[build-dependencies] -napi-build = "2" diff --git a/native/build.rs b/native/build.rs deleted file mode 100644 index 0f1b010..0000000 --- a/native/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - napi_build::setup(); -} diff --git a/package-lock.json b/package-lock.json index 3a73c3d..3597bdf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "wechaty-puppet-neo", - "version": "0.1.2", + "version": "0.1.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "wechaty-puppet-neo", - "version": "0.1.2", + "version": "0.1.3", "license": "Apache-2.0", "dependencies": { "jsqr": "1.4.0", diff --git a/package.json b/package.json index 70dfd5b..79b044a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wechaty-puppet-neo", - "version": "0.1.2", + "version": "0.1.3", "description": "A standalone WeChat protocol Puppet for Wechaty", "type": "module", "main": "./dist/index.js", @@ -13,8 +13,9 @@ }, "files": [ "dist", - "native/*/neo.node", - "native/*/THIRD-PARTY.txt", + "wasm/pkg/neo.js", + "wasm/pkg/neo_bg.wasm", + "wasm/pkg/THIRD-PARTY.txt", "examples/ding-dong-bot.ts", "docs/v1-spec.md" ], @@ -29,7 +30,7 @@ }, "scripts": { "build": "tsc", - "build:native": "node scripts/build-native.mjs", + "build:wasm": "node scripts/build-wasm.mjs", "typecheck": "tsc --project tsconfig.check.json", "test": "npm run build && npm run typecheck && node --test test/*.test.ts", "ding-dong": "node examples/ding-dong-bot.ts", diff --git a/rust-toolchain.toml b/rust-toolchain.toml index ee43e83..51c5934 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,4 @@ [toolchain] channel = "1.93.1" components = ["rustfmt", "clippy"] +targets = ["wasm32-unknown-unknown"] diff --git a/scripts/build-native.mjs b/scripts/build-native.mjs deleted file mode 100644 index 0dffa60..0000000 --- a/scripts/build-native.mjs +++ /dev/null @@ -1,41 +0,0 @@ -import { copyFileSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' -import { execFileSync, spawnSync } from 'node:child_process' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import platforms from '../src/native-platforms.json' with { type: 'json' } - -const root = fileURLToPath(new URL('../', import.meta.url)) -const platform = `${process.platform}-${process.arch}` -const config = platforms[platform] -if (!config) throw new Error(`Neo has no native build for ${platform}`) -if (process.platform === 'linux' && !process.report.getReport().header.glibcVersionRuntime) { - throw new Error('Neo requires glibc on Linux') -} -const { status, error } = spawnSync('cargo', [ - 'build', '--release', '--locked', '--manifest-path', 'native/Cargo.toml', - '--target-dir', 'native/target', '--target', config.target, -], { cwd: root, stdio: 'inherit' }) -if (error) throw error -if (status !== 0) process.exit(status ?? 1) - -const metadata = JSON.parse(execFileSync('cargo', [ - 'metadata', '--locked', '--format-version', '1', '--manifest-path', 'native/Cargo.toml', - '--filter-platform', config.target, -], { cwd: root, encoding: 'utf8' })) -const notices = metadata.packages - .filter(pkg => pkg.source) - .sort((a, b) => a.name.localeCompare(b.name)) - .map(pkg => { - const directory = dirname(pkg.manifest_path) - const paths = new Set(readdirSync(directory, { withFileTypes: true }) - .filter(entry => entry.isFile() && /^(license|licence|notice|copying|copyright|unlicense)([._-].*)?$/i.test(entry.name)) - .map(entry => entry.name)) - if (pkg.license_file) paths.add(pkg.license_file) - if (pkg.name === 'openssl-src') paths.add('openssl/LICENSE.txt') - return [`${pkg.name} ${pkg.version} (${pkg.license ?? 'see license text'})`, pkg.repository, - ...[...paths].sort().map(path => readFileSync(join(directory, path), 'utf8'))].filter(Boolean).join('\n\n') - }) -const output = join(root, 'native', platform) -mkdirSync(output, { recursive: true }) -copyFileSync(join(root, 'native', 'target', config.target, 'release', config.binary), join(output, 'neo.node')) -writeFileSync(join(output, 'THIRD-PARTY.txt'), notices.join('\n\n---\n\n')) diff --git a/scripts/build-wasm.mjs b/scripts/build-wasm.mjs new file mode 100644 index 0000000..af0d116 --- /dev/null +++ b/scripts/build-wasm.mjs @@ -0,0 +1,49 @@ +// Build Neo's WebAssembly session and its Node bindings into wasm/pkg. +import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { execFileSync, spawnSync } from 'node:child_process' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = fileURLToPath(new URL('../', import.meta.url)) +const target = 'wasm32-unknown-unknown' +const manifest = ['--manifest-path', 'wasm/Cargo.toml'] + +function run(command, args) { + const { status, error } = spawnSync(command, args, { cwd: root, stdio: 'inherit' }) + if (error) throw error + if (status !== 0) process.exit(status ?? 1) +} + +const metadata = JSON.parse(execFileSync('cargo', [ + 'metadata', '--locked', '--format-version', '1', ...manifest, '--filter-platform', target, +], { cwd: root, encoding: 'utf8' })) + +// wasm-bindgen's command-line tool must match the crate version in Cargo.lock. +const bindgen = metadata.packages.find(pkg => pkg.name === 'wasm-bindgen' && pkg.source) +const tool = spawnSync('wasm-bindgen', ['--version'], { encoding: 'utf8' }) +if (tool.error || !tool.stdout.includes(bindgen.version)) { + throw new Error(`Install wasm-bindgen ${bindgen.version}: cargo install --locked wasm-bindgen-cli --version ${bindgen.version}`) +} + +run('cargo', ['build', '--release', '--locked', ...manifest, '--target', target]) +const output = join(root, 'wasm', 'pkg') +rmSync(output, { recursive: true, force: true }) +run('wasm-bindgen', [ + '--target', 'experimental-nodejs-module', '--out-dir', output, '--out-name', 'neo', + join(root, 'wasm', 'target', target, 'release', 'puppet_neo_wasm.wasm'), +]) + +const notices = metadata.packages + .filter(pkg => pkg.source) + .sort((a, b) => a.name.localeCompare(b.name)) + .map(pkg => { + const directory = dirname(pkg.manifest_path) + const paths = new Set(readdirSync(directory, { withFileTypes: true }) + .filter(entry => entry.isFile() && /^(license|licence|notice|copying|copyright|unlicense)([._-].*)?$/i.test(entry.name)) + .map(entry => entry.name)) + if (pkg.license_file) paths.add(pkg.license_file) + return [`${pkg.name} ${pkg.version} (${pkg.license ?? 'see license text'})`, pkg.repository, + ...[...paths].sort().map(path => readFileSync(join(directory, path), 'utf8'))].filter(Boolean).join('\n\n') + }) +mkdirSync(output, { recursive: true }) +writeFileSync(join(output, 'THIRD-PARTY.txt'), `${notices.join('\n\n---\n\n')}\n`) diff --git a/scripts/test-package.mjs b/scripts/test-package.mjs index 82fdf59..d2850f3 100644 --- a/scripts/test-package.mjs +++ b/scripts/test-package.mjs @@ -3,14 +3,11 @@ import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import platforms from '../src/native-platforms.json' with { type: 'json' } const root = fileURLToPath(new URL('../', import.meta.url)) const npmCli = process.env.npm_execpath if (!npmCli) throw new Error('Run this check with npm run test:package') const destination = process.argv[2] ? resolve(process.argv[2]) : undefined -const platform = `${process.platform}-${process.arch}` -const requiredPlatforms = destination ? Object.keys(platforms) : [platform] const scratch = mkdtempSync(join(tmpdir(), 'neo-pack-')) const env = { ...process.env } // npm rejects a project install with the parent npm script's allow-scripts flag. @@ -29,8 +26,8 @@ function run(command, args, cwd, capture = false) { try { const [pack] = JSON.parse(run(process.execPath, [npmCli, 'pack', '--json', '--pack-destination', scratch], root, true)) const expectedFiles = [ - 'dist/index.js', 'dist/native-platforms.json', 'docs/v1-spec.md', 'examples/ding-dong-bot.ts', - ...requiredPlatforms.flatMap(key => [`native/${key}/neo.node`, `native/${key}/THIRD-PARTY.txt`]), + 'dist/index.js', 'dist/host.js', 'docs/v1-spec.md', 'examples/ding-dong-bot.ts', + 'wasm/pkg/neo.js', 'wasm/pkg/neo_bg.wasm', 'wasm/pkg/THIRD-PARTY.txt', ] for (const expected of expectedFiles) { if (!pack.files.some(file => file.path === expected)) throw new Error(`Packed artifact is missing ${expected}`) @@ -39,7 +36,7 @@ try { run(process.execPath, [npmCli, 'install', '--ignore-scripts', '--no-audit', join(scratch, pack.filename)], scratch) mkdirSync(join(scratch, 'test')) mkdirSync(join(scratch, 'examples')) - const tests = ['ding-dong.test.ts', 'native.test.ts'] + const tests = ['ding-dong.test.ts', 'session.test.ts'] for (const test of tests) copyFileSync(join(root, 'test', test), join(scratch, 'test', test)) copyFileSync(join(scratch, 'node_modules', 'wechaty-puppet-neo', 'examples', 'ding-dong-bot.ts'), join(scratch, 'examples', 'ding-dong-bot.ts')) run(process.execPath, ['--test', ...tests.map(test => join('test', test))], scratch) diff --git a/src/host.ts b/src/host.ts new file mode 100644 index 0000000..69c23fb --- /dev/null +++ b/src/host.ts @@ -0,0 +1,150 @@ +import { connect as tcpConnect, type Socket } from 'node:net' +import { setTimeout as delay } from 'node:timers/promises' + +/** Why a host operation failed, in the terms the protocol uses to decide retries. */ +type FailureCode = 'timeout' | 'interrupted' | 'disconnected' + +class HostError extends Error { + readonly code: FailureCode + + constructor(code: FailureCode, message: string) { + super(message) + this.code = code + } +} + +// Stop reading from the socket while this much received data waits to be read. +const HIGH_WATER = 1024 * 1024 + +interface Stream { + socket: Socket + chunks: Buffer[] + queued: number + ended: boolean + failure?: HostError + wake?: () => void +} + +/** + * Network and time for Neo's WebAssembly session: TCP connections through + * Node's `net` module and Node's clocks. Read results follow the session's + * contract: bytes, `null` at the end of the stream, or `undefined` when + * nothing arrived in time. + */ +export class NeoHost { + #streams = new Map() + #nextId = 1 + + connect(host: string, port: number, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + const socket = tcpConnect({ host, port, noDelay: true }) + const timer = setTimeout(() => { + socket.destroy() + reject(new HostError('timeout', `Connecting to ${host}:${port} timed out`)) + }, timeoutMs) + socket.once('error', (error) => { + clearTimeout(timer) + socket.destroy() + reject(new HostError('disconnected', `Could not connect to ${host}:${port}: ${error.message}`)) + }) + socket.once('connect', () => { + clearTimeout(timer) + socket.removeAllListeners('error') + const id = this.#nextId++ + this.#streams.set(id, this.#watch(socket)) + resolve(id) + }) + }) + } + + async read(id: number, maxBytes: number, timeoutMs: number): Promise { + const stream = this.#stream(id) + if (!stream.queued && !stream.ended && !stream.failure) { + const arrived = new Promise(resolve => { stream.wake = resolve }) + const timeout = new AbortController() + await Promise.race([arrived, delay(timeoutMs, undefined, { signal: timeout.signal }).catch(() => {})]) + timeout.abort() + stream.wake = undefined + } + if (stream.queued) return this.#take(stream, maxBytes) + if (stream.failure) throw stream.failure + return stream.ended ? null : undefined + } + + write(id: number, bytes: Uint8Array, timeoutMs: number): Promise { + const stream = this.#stream(id) + if (stream.failure) return Promise.reject(stream.failure) + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new HostError('timeout', 'Writing to the connection timed out')) + }, timeoutMs) + stream.socket.write(bytes, (error) => { + clearTimeout(timer) + if (error) reject(new HostError('interrupted', `Writing to the connection failed: ${error.message}`)) + else resolve() + }) + }) + } + + close(id: number): void { + this.#streams.get(id)?.socket.destroy() + this.#streams.delete(id) + } + + monotonicMs(): number { + return Math.floor(performance.now()) + } + + unixTimeMs(): number { + return Date.now() + } + + sleep(ms: number): Promise { + return delay(ms) + } + + #watch(socket: Socket): Stream { + const stream: Stream = { socket, chunks: [], queued: 0, ended: false } + socket.on('data', (chunk: Buffer) => { + stream.chunks.push(chunk) + stream.queued += chunk.length + if (stream.queued >= HIGH_WATER) socket.pause() + stream.wake?.() + }) + socket.on('end', () => { + stream.ended = true + stream.wake?.() + }) + socket.on('error', (error) => { + stream.failure = new HostError('interrupted', `The connection failed: ${error.message}`) + stream.wake?.() + }) + socket.on('close', () => { + stream.ended = true + stream.wake?.() + }) + return stream + } + + #take(stream: Stream, maxBytes: number): Uint8Array { + const parts: Buffer[] = [] + let length = 0 + while (stream.chunks.length && length < maxBytes) { + const chunk = stream.chunks[0]! + const part = chunk.subarray(0, maxBytes - length) + parts.push(part) + length += part.length + if (part.length === chunk.length) stream.chunks.shift() + else stream.chunks[0] = chunk.subarray(part.length) + } + stream.queued -= length + if (stream.queued < HIGH_WATER && stream.socket.isPaused()) stream.socket.resume() + return Buffer.concat(parts, length) + } + + #stream(id: number): Stream { + const stream = this.#streams.get(id) + if (!stream) throw new HostError('disconnected', 'The connection is closed') + return stream + } +} diff --git a/src/native-platforms.json b/src/native-platforms.json deleted file mode 100644 index db92c43..0000000 --- a/src/native-platforms.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "linux-x64": { "target": "x86_64-unknown-linux-gnu", "binary": "libpuppet_neo_native.so" }, - "linux-arm64": { "target": "aarch64-unknown-linux-gnu", "binary": "libpuppet_neo_native.so" }, - "darwin-arm64": { "target": "aarch64-apple-darwin", "binary": "libpuppet_neo_native.dylib" }, - "win32-x64": { "target": "x86_64-pc-windows-msvc", "binary": "puppet_neo_native.dll" } -} diff --git a/src/native.ts b/src/native.ts deleted file mode 100644 index eea2d34..0000000 --- a/src/native.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { createRequire } from 'node:module' -import platforms from './native-platforms.json' with { type: 'json' } - -/** Error message for a session that WeChat no longer accepts. */ -export const SESSION_ENDED = 'Neo session ended by WeChat' - -export interface SelfProfile { - nickname: string | null - alias: string | null - avatar: string | null -} - -export interface IncomingText { - id: string - /** Who wrote the message; in a group, the member who posted it. */ - talker: string - /** The account that received a direct message. */ - listener?: string - /** The group the message was posted in. */ - room?: string - text: string - timestamp: number -} - -export interface Session { - startLogin(): Promise<{ png: string }> - pollLogin(): Promise< - | { status: 'pending' | 'scanned' | 'retry' | 'expired' | 'cancelled' | 'rejected' } - | { status: 'completed', username: string } - > - heartbeat(): Promise<{ sync: boolean, intervalMs: number }> - pollIncoming(): Promise - sync(scene: 1 | 6 | 7): Promise<{ messages: IncomingText[], continuation: boolean }> - sendText(destination: string, text: string): Promise<{ status: 'accepted' | 'rejected' | 'uncertain' }> - lookupSelf(): Promise - logout(): Promise<{ accepted: boolean }> - close(): Promise -} - -type Addon = { [K in keyof Session]: (...args: Parameters) => Promise } - -export function openNativeSession(): Session { - const platform = `${process.platform}-${process.arch}` - if (platform === 'win32-arm64') { - throw new Error('Run Neo with x64 Node.js on Windows 11 on ARM') - } - if (!Object.hasOwn(platforms, platform)) { - throw new Error(`Neo has no native build for ${platform}`) - } - const report = process.report.getReport() as { header: { glibcVersionRuntime?: string } } - if (process.platform === 'linux' && !report.header.glibcVersionRuntime) { - throw new Error('Neo requires glibc on Linux') - } - const require = createRequire(import.meta.url) - const addonPath = `../native/${platform}/neo.node` - try { - require.resolve(addonPath) - } catch (error) { - throw new Error(`Neo native addon missing for ${platform}. Install a package for this platform or run npm run build:native from a source checkout.`, { cause: error }) - } - const { NeoSession } = require(addonPath) as { NeoSession: new () => Addon } - const addon = new NeoSession() - - return { - startLogin: async () => JSON.parse(await addon.startLogin()), - pollLogin: async () => JSON.parse(await addon.pollLogin()), - heartbeat: async () => JSON.parse(await addon.heartbeat()), - pollIncoming: async () => JSON.parse(await addon.pollIncoming()), - sync: async (scene) => JSON.parse(await addon.sync(scene)), - sendText: async (destination, text) => JSON.parse(await addon.sendText(destination, text)), - lookupSelf: async () => JSON.parse(await addon.lookupSelf()), - logout: async () => JSON.parse(await addon.logout()), - close: async () => { await addon.close() }, - } -} diff --git a/src/puppet-neo.ts b/src/puppet-neo.ts index d082c89..16835a9 100644 --- a/src/puppet-neo.ts +++ b/src/puppet-neo.ts @@ -2,7 +2,7 @@ import { setTimeout as delay } from 'node:timers/promises' import { types, type payloads, type PuppetOptions } from 'wechaty-puppet' import jsQR from 'jsqr' import { PNG } from 'pngjs' -import { openNativeSession, SESSION_ENDED, type SelfProfile, type Session } from './native.js' +import { openSession, SESSION_ENDED, type SelfProfile, type Session } from './session.js' import { PuppetUnsupported } from './unsupported.js' const CACHE_LIMIT = 2048 @@ -31,7 +31,7 @@ function decodeQr(encoded: string) { } export class PuppetNeo extends PuppetUnsupported { - static override readonly VERSION = '0.1.2' + static override readonly VERSION = '0.1.3' private run?: Promise private abort?: AbortController @@ -48,7 +48,7 @@ export class PuppetNeo extends PuppetUnsupported { } protected createSession(): Session { - return openNativeSession() + return openSession() } protected scanCode(png: string): string { diff --git a/src/session.ts b/src/session.ts new file mode 100644 index 0000000..9531fed --- /dev/null +++ b/src/session.ts @@ -0,0 +1,69 @@ +import { createRequire } from 'node:module' +import { NeoHost } from './host.js' + +/** Error message for a session that WeChat no longer accepts. */ +export const SESSION_ENDED = 'Neo session ended by WeChat' + +export interface SelfProfile { + nickname: string | null + alias: string | null + avatar: string | null +} + +export interface IncomingText { + id: string + /** Who wrote the message; in a group, the member who posted it. */ + talker: string + /** The account that received a direct message. */ + listener?: string + /** The group the message was posted in. */ + room?: string + text: string + timestamp: number +} + +export interface Session { + startLogin(): Promise<{ png: string }> + pollLogin(): Promise< + | { status: 'pending' | 'scanned' | 'retry' | 'expired' | 'cancelled' | 'rejected' } + | { status: 'completed', username: string } + > + heartbeat(): Promise<{ sync: boolean, intervalMs: number }> + pollIncoming(): Promise + sync(scene: 1 | 6 | 7): Promise<{ messages: IncomingText[], continuation: boolean }> + sendText(destination: string, text: string): Promise<{ status: 'accepted' | 'rejected' | 'uncertain' }> + lookupSelf(): Promise + logout(): Promise<{ accepted: boolean }> + close(): Promise +} + +type Bindings = { + NeoSession: new (host: NeoHost) => { [K in keyof Session]: (...args: Parameters) => Promise } +} + +/** + * Open a WeChat session. The protocol runs in WebAssembly, so one build works on + * every platform Node.js runs on; Node supplies the TCP connections. + */ +export function openSession(): Session { + const require = createRequire(import.meta.url) + let bindings: Bindings + try { + bindings = require('../wasm/pkg/neo.js') as Bindings + } catch (error) { + throw new Error('Neo WebAssembly session missing. Install the package from npm or run npm run build:wasm from a source checkout.', { cause: error }) + } + const wasm = new bindings.NeoSession(new NeoHost()) + + return { + startLogin: async () => JSON.parse(await wasm.startLogin()), + pollLogin: async () => JSON.parse(await wasm.pollLogin()), + heartbeat: async () => JSON.parse(await wasm.heartbeat()), + pollIncoming: async () => JSON.parse(await wasm.pollIncoming()), + sync: async (scene) => JSON.parse(await wasm.sync(scene)), + sendText: async (destination, text) => JSON.parse(await wasm.sendText(destination, text)), + lookupSelf: async () => JSON.parse(await wasm.lookupSelf()), + logout: async () => JSON.parse(await wasm.logout()), + close: async () => { await wasm.close() }, + } +} diff --git a/test/ding-dong.test.ts b/test/ding-dong.test.ts index b5463dd..9a9e884 100644 --- a/test/ding-dong.test.ts +++ b/test/ding-dong.test.ts @@ -4,7 +4,7 @@ import { test } from 'node:test' import { types, type payloads } from 'wechaty-puppet' import qrTerminal from 'qrcode-terminal' import PuppetNeo from 'wechaty-puppet-neo' -import type { IncomingText, SelfProfile, Session } from '../src/native.js' +import type { IncomingText, SelfProfile, Session } from '../src/session.js' const username = 'fixture-self' const sender = 'fixture-peer' @@ -12,7 +12,7 @@ const room = 'fixture-room@chatroom' const member = 'fixture-member' const direct: IncomingText = { id: 'fixture-message', talker: sender, listener: username, text: 'ding', timestamp: 1700000000 } const inRoom: IncomingText = { id: 'fixture-room-message', talker: member, room, text: 'ding', timestamp: 1700000001 } -// The native addon's error for a session WeChat no longer accepts (SESSION_ENDED). +// The WebAssembly session's error for a session WeChat no longer accepts (SESSION_ENDED). const SESSION_ENDED = 'Neo session ended by WeChat' const profile: SelfProfile = { nickname: 'Fixture Name', alias: 'fixture-alias', avatar: null } diff --git a/test/native.test.ts b/test/session.test.ts similarity index 84% rename from test/native.test.ts rename to test/session.test.ts index 2ad5837..6de6295 100644 --- a/test/native.test.ts +++ b/test/session.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import { test } from 'node:test' import PuppetNeo from 'wechaty-puppet-neo' -test('the compiled addon starts without a storage key and rejects unauthenticated operations', async () => { +test('the WebAssembly session starts and rejects unauthenticated operations', async () => { const puppet = new class extends PuppetNeo { openSession() { return this.createSession() } }() diff --git a/native/Cargo.lock b/wasm/Cargo.lock similarity index 69% rename from native/Cargo.lock rename to wasm/Cargo.lock index 19c9a27..445ffaa 100644 --- a/native/Cargo.lock +++ b/wasm/Cargo.lock @@ -8,11 +8,48 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", + "zeroize", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", + "zeroize", +] + [[package]] name = "anyhow" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" [[package]] name = "atomic-waker" @@ -26,6 +63,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" @@ -38,17 +81,41 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "bytemuck" @@ -64,15 +131,24 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" [[package]] name = "bytes" -version = "1.12.1" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cbc" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] [[package]] name = "cc" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", "shlex", @@ -90,6 +166,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + [[package]] name = "chacha20" version = "0.10.2" @@ -97,8 +184,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures", - "rand_core", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", ] [[package]] @@ -108,12 +206,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" [[package]] -name = "convert_case" -version = "0.12.0" +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "constant_time_eq" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" dependencies = [ - "unicode-segmentation", + "rustversion", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", ] [[package]] @@ -127,18 +240,66 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.4" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" dependencies = [ "cfg-if", ] [[package]] -name = "ctor" -version = "1.0.13" +name = "crypto-bigint" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] [[package]] name = "displaydoc" @@ -148,14 +309,54 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -176,43 +377,38 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "find-msvc-tools" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" [[package]] name = "flate2" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", "miniz_oxide 0.9.1", "zlib-rs", ] -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -265,17 +461,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "futures-sink" version = "0.3.34" @@ -297,7 +482,6 @@ dependencies = [ "futures-channel", "futures-core", "futures-io", - "futures-macro", "futures-sink", "futures-task", "memchr", @@ -305,6 +489,17 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -328,10 +523,20 @@ dependencies = [ "js-sys", "libc", "r-efi", - "rand_core", + "rand_core 0.10.1", "wasm-bindgen", ] +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + [[package]] name = "gif" version = "0.14.2" @@ -342,17 +547,52 @@ dependencies = [ "weezl", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + [[package]] name = "hex" 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", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" dependencies = [ "bytes", "itoa", @@ -389,9 +629,9 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hyper" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" dependencies = [ "atomic-waker", "bytes", @@ -570,25 +810,51 @@ dependencies = [ [[package]] name = "image-webp" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +checksum = "7c8d2831f3eb9706eeac62164959a288f12c047a3c53b353c6c00d5d60eb5c7f" dependencies = [ "byteorder-lite", "quick-error", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + [[package]] name = "ipnet" -version = "2.12.2" +version = "2.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jpeg-decoder" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" [[package]] name = "js-sys" @@ -601,6 +867,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "libc" version = "0.2.191" @@ -608,14 +883,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] -name = "libloading" -version = "0.9.0" +name = "libm" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" -dependencies = [ - "cfg-if", - "windows-link", -] +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "linux-raw-sys" @@ -641,6 +912,16 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -669,9 +950,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", @@ -689,71 +970,52 @@ dependencies = [ ] [[package]] -name = "napi" -version = "3.16.1" +name = "nix" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "907ff7366fb7182e28edd0f08ef8ac5d6b13b8d65a3c0b3a10bf3ac092437d6b" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" dependencies = [ "bitflags", - "ctor", - "futures", + "cfg-if", + "cfg_aliases", "libc", - "napi-build", - "napi-sys", - "nohash-hasher", - "rustc-hash", - "serde", - "serde_json", ] [[package]] -name = "napi-build" -version = "2.6.0" +name = "num-bigint-dig" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" - -[[package]] -name = "napi-derive" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d32eb00f92f84cf462fc328f49082b29c2a7d2eebeb1d447d19c1f9fdd9f89ee" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" dependencies = [ - "convert_case", - "ctor", - "napi-derive-backend", - "proc-macro2", - "quote", - "syn 3.0.9", + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", ] [[package]] -name = "napi-derive-backend" -version = "7.0.0" +name = "num-integer" +version = "0.1.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1fe28c64d8fc12e69f9b817d0febdbe7914555760f1e353106281b8ff99cc90" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" dependencies = [ - "convert_case", - "proc-macro2", - "quote", - "semver", - "syn 3.0.9", + "num-traits", ] [[package]] -name = "napi-sys" -version = "3.4.1" +name = "num-iter" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d153beb7d5c973f4b9395be8a83054a28968b61188f1dd1a2cc2321af22daea2" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" dependencies = [ - "libloading", + "num-integer", + "num-traits", ] -[[package]] -name = "nohash-hasher" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" - [[package]] name = "num-traits" version = "0.2.19" @@ -761,6 +1023,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -770,50 +1033,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] -name = "openssl" -version = "0.10.82" +name = "opaque-debug" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "openssl-macros", - "openssl-sys", -] +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] -name = "openssl-macros" -version = "0.1.1" +name = "p224" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +checksum = "30c06436d66652bc2f01ade021592c80a2aad401570a18aa18b82e440d2b9aa1" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "elliptic-curve", + "primeorder", ] [[package]] -name = "openssl-src" -version = "300.6.1+3.6.3" +name = "p256" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ - "cc", + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", ] [[package]] -name = "openssl-sys" -version = "0.9.118" +name = "pem-rfc7468" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" dependencies = [ - "cc", - "libc", - "openssl-src", - "pkg-config", - "vcpkg", + "base64ct", ] [[package]] @@ -824,15 +1077,30 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] -name = "pkg-config" -version = "0.3.34" +name = "pkcs1" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] [[package]] name = "png" @@ -847,6 +1115,30 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", + "zeroize", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -856,6 +1148,24 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -866,17 +1176,18 @@ dependencies = [ ] [[package]] -name = "puppet-neo-native" +name = "puppet-neo-wasm" version = "0.1.0" dependencies = [ "anyhow", "base64 0.22.1", - "napi", - "napi-build", - "napi-derive", - "openssl", + "futures", + "getrandom 0.4.3", + "js-sys", "serde", "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", "wechat-protocol", ] @@ -921,7 +1232,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.4", "rand_pcg", "ring", "rustc-hash", @@ -965,15 +1276,41 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.10.3" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ - "chacha20", + "chacha20 0.10.2", "getrandom 0.4.3", - "rand_core", + "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_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + [[package]] name = "rand_core" version = "0.10.1" @@ -982,11 +1319,11 @@ checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] name = "rand_pcg" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" dependencies = [ - "rand_core", + "rand_core 0.10.1", ] [[package]] @@ -1029,6 +1366,16 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -1043,6 +1390,35 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -1064,9 +1440,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.46" +version = "0.23.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +checksum = "4ac0e747c10d93d873fd4c50b26ef47ad92d1bfb48f6922003bb514070f6e88c" dependencies = [ "once_cell", "ring", @@ -1078,9 +1454,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -1088,9 +1464,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.16" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "ring", "rustls-pki-types", @@ -1110,10 +1486,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] -name = "semver" -version = "1.0.28" +name = "sec1" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] [[package]] name = "serde" @@ -1142,7 +1526,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1170,6 +1554,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -1177,13 +1572,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] -name = "signal-hook-registry" -version = "1.4.8" +name = "signature" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "errno", - "libc", + "digest", + "rand_core 0.6.4", ] [[package]] @@ -1200,9 +1595,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.4" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" [[package]] name = "socket2" @@ -1214,6 +1609,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1239,9 +1650,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -1265,7 +1676,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1298,7 +1709,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1327,7 +1738,6 @@ dependencies = [ "libc", "mio", "pin-project-lite", - "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", @@ -1341,7 +1751,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1424,6 +1834,18 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -1431,10 +1853,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] -name = "unicode-segmentation" -version = "1.13.3" +name = "universal-hash" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] [[package]] name = "untrusted" @@ -1444,9 +1870,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -1470,10 +1896,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] -name = "vcpkg" -version = "0.2.15" +name = "version_check" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "want" @@ -1532,7 +1958,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] @@ -1567,32 +1993,38 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] [[package]] name = "wechat-media" -version = "2.2.0" +version = "3.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a2c73860c253078189fbc1dfc9ffce41d8284896e965af9a531a293b8fe024e" +checksum = "2390635ddfda1bac8ecc6d40edd4dfe952fe5fd73fd46022a4fb456f056c3ae5" dependencies = [ "anyhow", + "gif", "image", + "jpeg-decoder", "libc", + "md-5", "serde", + "serde_json", + "sha2", "tempfile", "wechat-platform", + "zip", ] [[package]] name = "wechat-platform" -version = "2.2.0" +version = "3.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8ca5031024938d972e45432766a5eec67efd795549f39b0738b07da069e260" +checksum = "7f905e015ba6d44eed0abc1733f0c714e02f73826301f1c7f73c9371b6694ef9" dependencies = [ "libc", "tempfile", @@ -1601,21 +2033,37 @@ dependencies = [ [[package]] name = "wechat-protocol" -version = "2.2.0" +version = "3.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31dd60cd137a312e5b531d8ea9ea4115939e64284a97d261c33a2be572308ff7" +checksum = "0d2c2d887f9f2496b7231855f413d75712aaf8c439d60e755ed660a12980bfed" dependencies = [ + "aes", + "aes-gcm", "anyhow", "base64 0.22.1", - "cc", + "cbc", + "chacha20 0.9.1", + "digest", "flate2", + "getrandom 0.4.3", "hex", + "hmac", "image", - "openssl", + "md-5", + "p224", + "p256", + "pkcs8", + "poly1305", + "rand_core 0.6.4", "reqwest", + "roxmltree", + "rsa", "serde", "serde_json", + "sha2", + "subtle", "tokio", + "url", "wechat-media", "wechat-platform", "zeroize", @@ -1740,10 +2188,30 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -1761,15 +2229,15 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] [[package]] name = "zeroize" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" dependencies = [ "zeroize_derive", ] @@ -1815,14 +2283,34 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", +] + +[[package]] +name = "zip" +version = "9.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", + "zopfli", ] [[package]] name = "zlib-rs" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" [[package]] name = "zmij" @@ -1830,11 +2318,23 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zune-core" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18" [[package]] name = "zune-jpeg" diff --git a/wasm/Cargo.toml b/wasm/Cargo.toml new file mode 100644 index 0000000..63f2f96 --- /dev/null +++ b/wasm/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "puppet-neo-wasm" +version = "0.1.0" +edition = "2024" +rust-version = "1.93.1" +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +anyhow = "1" +base64 = "0.22" +futures = { version = "0.3", default-features = false, features = ["std", "executor"] } +getrandom = { version = "0.4", features = ["wasm_js"] } +js-sys = "=0.3.107" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +wasm-bindgen = "=0.2.130" +wasm-bindgen-futures = "=0.4.80" +wechat-protocol = { version = "=3.8.0", default-features = false, features = ["pure-rust-crypto"] } + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 diff --git a/wasm/src/host.rs b/wasm/src/host.rs new file mode 100644 index 0000000..cace093 --- /dev/null +++ b/wasm/src/host.rs @@ -0,0 +1,210 @@ +//! The protocol's network and clock, supplied by the JavaScript host. Neo's +//! TypeScript layer passes a `NeoHost` (src/host.ts) that opens TCP connections +//! with Node's `net` module. WebAssembly has no sockets or clock of its own. + +use std::{rc::Rc, sync::Arc, time::Duration}; + +use anyhow::{Result, anyhow, ensure}; +use js_sys::{Promise, Reflect, Uint8Array}; +use wasm_bindgen::{JsCast, prelude::*}; +use wasm_bindgen_futures::JsFuture; +use wechat_protocol::transport::{ + AsyncByteStream, Clock, ProtocolTransport, ReadOutcome, StreamTransport, TaskSpawner, + TransportError, TransportFuture, +}; + +#[wasm_bindgen] +extern "C" { + /// Network and time for the protocol. Rejected promises carry a `code` of + /// `"timeout"`, `"interrupted"` or `"disconnected"`. + pub type NeoHost; + + /// Open a TCP connection and resolve to its stream ID. + #[wasm_bindgen(method, catch)] + fn connect(this: &NeoHost, host: &str, port: u16, timeout_ms: f64) -> Result; + + /// Resolve to 1..=maxBytes bytes, `null` at the end of the stream, or + /// `undefined` when nothing arrived before the timeout. + #[wasm_bindgen(method, catch)] + fn read( + this: &NeoHost, + stream: u32, + max_bytes: u32, + timeout_ms: f64, + ) -> Result; + + #[wasm_bindgen(method, catch)] + fn write( + this: &NeoHost, + stream: u32, + bytes: &Uint8Array, + timeout_ms: f64, + ) -> Result; + + /// Close the stream at once; never waits. + #[wasm_bindgen(method)] + fn close(this: &NeoHost, stream: u32); + + /// Milliseconds from a clock that never goes backwards. + #[wasm_bindgen(method, js_name = monotonicMs)] + fn monotonic_ms(this: &NeoHost) -> f64; + + #[wasm_bindgen(method, js_name = unixTimeMs)] + fn unix_time_ms(this: &NeoHost) -> f64; + + #[wasm_bindgen(method, catch)] + fn sleep(this: &NeoHost, ms: f64) -> Result; +} + +/// A protocol transport over the host's TCP and clock. Account work detaches +/// onto the JavaScript event loop, so a dropped call never strands a request. +#[allow( + clippy::arc_with_non_send_sync, + reason = "ProtocolTransport takes Arcs; WebAssembly runs on one thread" +)] +pub fn transport(host: NeoHost) -> ProtocolTransport { + let host = Rc::new(host); + ProtocolTransport::from_streams( + Arc::new(HostStreams(host.clone())), + Arc::new(HostClock(host)), + ) + .with_spawner(Arc::new(EventLoop)) +} + +fn millis(duration: Duration) -> f64 { + duration.as_millis() as f64 +} + +/// The protocol decides retries from the transport error kind, so host +/// failures keep it instead of becoming plain text. +fn host_error(error: JsValue) -> anyhow::Error { + let code = Reflect::get(&error, &JsValue::from_str("code")) + .ok() + .and_then(|code| code.as_string()); + anyhow::Error::new(match code.as_deref() { + Some("timeout") => TransportError::Timeout, + Some("interrupted") => TransportError::Interrupted, + _ => TransportError::Disconnected, + }) +} + +async fn settle(promise: Result) -> Result { + JsFuture::from(promise.map_err(host_error)?) + .await + .map_err(host_error) +} + +struct HostStreams(Rc); + +impl StreamTransport for HostStreams { + fn connect<'a>( + &'a self, + host: &'a str, + port: u16, + timeout: Duration, + ) -> TransportFuture<'a, Result>> { + Box::pin(async move { + let id = settle(self.0.connect(host, port, millis(timeout))) + .await? + .as_f64() + .ok_or_else(|| anyhow!("The host returned no stream ID"))?; + Ok(Box::new(HostStream { + host: self.0.clone(), + id: id as u32, + open: true, + }) as Box) + }) + } +} + +struct HostStream { + host: Rc, + id: u32, + open: bool, +} + +impl AsyncByteStream for HostStream { + fn read<'a>( + &'a mut self, + buf: &'a mut [u8], + timeout: Duration, + ) -> TransportFuture<'a, Result> { + Box::pin(async move { + let max = u32::try_from(buf.len()).unwrap_or(u32::MAX); + let value = settle(self.host.read(self.id, max, millis(timeout))).await?; + if value.is_undefined() { + return Ok(ReadOutcome::TimedOut); + } + if value.is_null() { + return Ok(ReadOutcome::Eof); + } + let bytes: Uint8Array = value + .dyn_into() + .map_err(|_| anyhow!("The host returned no bytes"))?; + let length = bytes.length() as usize; + ensure!( + (1..=buf.len()).contains(&length), + "The host returned {length} bytes for a {}-byte read", + buf.len() + ); + bytes.copy_to(&mut buf[..length]); + Ok(ReadOutcome::Bytes(length)) + }) + } + + fn write_all<'a>( + &'a mut self, + buf: &'a [u8], + timeout: Duration, + ) -> TransportFuture<'a, Result<()>> { + Box::pin(async move { + // A copy outside WebAssembly memory, which can move while the write is pending. + let bytes = Uint8Array::from(buf); + settle(self.host.write(self.id, &bytes, millis(timeout))).await?; + Ok(()) + }) + } + + fn close<'a>(&'a mut self) -> TransportFuture<'a, Result<()>> { + Box::pin(async move { + if std::mem::take(&mut self.open) { + self.host.close(self.id); + } + Ok(()) + }) + } +} + +impl Drop for HostStream { + fn drop(&mut self) { + if self.open { + self.host.close(self.id); + } + } +} + +struct HostClock(Rc); + +impl Clock for HostClock { + fn monotonic_ms(&self) -> u64 { + self.0.monotonic_ms() as u64 + } + + fn unix_time_ms(&self) -> Result { + Ok(self.0.unix_time_ms() as u64) + } + + fn sleep<'a>(&'a self, duration: Duration) -> TransportFuture<'a, ()> { + Box::pin(async move { + let _ = settle(self.0.sleep(millis(duration))).await; + }) + } +} + +struct EventLoop; + +impl TaskSpawner for EventLoop { + fn spawn(&self, task: TransportFuture<'static, ()>) { + wasm_bindgen_futures::spawn_local(task); + } +} diff --git a/native/src/lib.rs b/wasm/src/lib.rs similarity index 57% rename from native/src/lib.rs rename to wasm/src/lib.rs index ec6c930..de5ea83 100644 --- a/native/src/lib.rs +++ b/wasm/src/lib.rs @@ -1,19 +1,24 @@ -use anyhow::{anyhow, ensure, Context, Result}; -use base64::{engine::general_purpose::STANDARD, Engine}; -use napi::{bindgen_prelude::AsyncTask, Env, Task}; -use napi_derive::napi; +#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +//! Neo's WeChat session, compiled to WebAssembly. The protocol runs here; the +//! JavaScript host supplies TCP connections and the clock (see `host`). + +use anyhow::{Context, Result, anyhow, ensure}; +use base64::{Engine, engine::general_purpose::STANDARD}; use serde::Serialize; -use serde_json::{json, Value}; -use std::{ - sync::{Arc, Mutex}, - time::{Duration, SystemTime, UNIX_EPOCH}, -}; +use serde_json::{Value, json}; +use std::time::Duration; use wechat_protocol::{ - is_session_rejected, wire, AccountInterrupted, AccountPushConnection, DeviceProfile, - LoginAttempt, LoginStatus, NativeClient, NativeOptions, Service, ServiceRejected, - TextSendOptions, + AccountInterrupted, AsyncPushConnection, DeviceProfile, LoginAttempt, LoginStatus, + NativeClient, NativeOptions, Service, ServiceRejected, TextSendOptions, is_session_rejected, + transport::ProtocolTransport, wire, }; +#[cfg(target_arch = "wasm32")] +mod host; +mod messages; + +use messages::text_messages; + const DEVICE_NAME: &str = "Puppet Neo"; /// Error text TypeScript receives when WeChat no longer accepts this session. const SESSION_ENDED: &str = "Neo session ended by WeChat"; @@ -32,29 +37,14 @@ impl std::error::Error for SessionEnded {} #[derive(Default)] struct Session { + transport: Option, attempt: Option, /// Owns the accepted credentials after login; account requests share it. account: Option, - incoming: Option, + incoming: Option, received_cursor: Vec, } -#[derive(Debug, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -struct TextMessage { - id: String, - /// Who wrote the message; in a group, the member who posted it. - talker: String, - /// The account that received a direct message. - #[serde(skip_serializing_if = "Option::is_none")] - listener: Option, - /// The group the message was posted in. - #[serde(skip_serializing_if = "Option::is_none")] - room: Option, - text: String, - timestamp: u32, -} - #[derive(Default, Serialize)] struct SelfProfile { nickname: Option, @@ -74,93 +64,9 @@ enum Operation { Close, } -#[napi] -#[derive(Default)] -pub struct NeoSession { - session: Arc>, -} - -#[napi] -impl NeoSession { - #[napi(constructor)] - pub fn new() -> Self { - Self::default() - } - - #[napi] - pub fn start_login(&self) -> AsyncTask { - self.task(Operation::StartLogin) - } - - #[napi] - pub fn poll_login(&self) -> AsyncTask { - self.task(Operation::PollLogin) - } - - #[napi] - pub fn heartbeat(&self) -> AsyncTask { - self.task(Operation::Heartbeat) - } - - #[napi] - pub fn sync(&self, scene: u32) -> AsyncTask { - self.task(Operation::Sync { scene }) - } - - #[napi] - pub fn poll_incoming(&self) -> AsyncTask { - self.task(Operation::PollIncoming) - } - - #[napi] - pub fn send_text(&self, destination: String, text: String) -> AsyncTask { - self.task(Operation::SendText { destination, text }) - } - - #[napi] - pub fn lookup_self(&self) -> AsyncTask { - self.task(Operation::LookupSelf) - } - - #[napi] - pub fn logout(&self) -> AsyncTask { - self.task(Operation::Logout) - } - - #[napi] - pub fn close(&self) -> AsyncTask { - self.task(Operation::Close) - } -} - -impl NeoSession { - fn task(&self, operation: Operation) -> AsyncTask { - AsyncTask::new(NeoTask { - session: self.session.clone(), - operation: Some(operation), - }) - } -} - -pub struct NeoTask { - session: Arc>, - operation: Option, -} - -impl Task for NeoTask { - type Output = Value; - type JsValue = String; - - fn compute(&mut self) -> napi::Result { - let mut session = self - .session - .lock() - .map_err(|_| napi::Error::from_reason("Neo session unavailable"))?; - let operation = self - .operation - .take() - .ok_or_else(|| napi::Error::from_reason("Operation already completed"))?; - let stage = match &operation { +impl Operation { + fn stage(&self) -> &'static str { + match self { Operation::StartLogin => "start QR login", Operation::PollLogin => "check or complete QR login", Operation::Heartbeat => "check session heartbeat", @@ -170,13 +76,7 @@ impl Task for NeoTask { Operation::LookupSelf => "look up the account profile", Operation::Logout => "log out", Operation::Close => "close the session", - }; - run(&mut session, operation) - .map_err(|error| napi::Error::from_reason(failure_message(stage, &error))) - } - - fn resolve(&mut self, _env: Env, output: Self::Output) -> napi::Result { - Ok(output.to_string()) + } } } @@ -202,7 +102,11 @@ fn options() -> NativeOptions { } } -fn run(session: &mut Session, operation: Operation) -> Result { +fn transport(session: &Session) -> Result { + session.transport.clone().context("No network host") +} + +async fn run(session: &mut Session, operation: Operation) -> Result { match operation { Operation::StartLogin => { ensure!( @@ -210,35 +114,42 @@ fn run(session: &mut Session, operation: Operation) -> Result { "Login already started" ); let device = DeviceProfile::generate("UnifiedPCLinux x86_64".into())?; - let attempt = NativeClient::new(options())?.start_qr_login(device, DEVICE_NAME)?; + let attempt = NativeClient::with_transport(options(), transport(session)?)? + .start_qr_login_async(device, DEVICE_NAME) + .await?; let output = json!({ "png": STANDARD.encode(&attempt.qr_png) }); session.attempt = Some(attempt); Ok(output) } Operation::PollLogin => { + let transport = transport(session)?; let attempt = session .attempt .as_mut() .ok_or_else(|| anyhow!("No login attempt"))?; - let client = NativeClient::new(options())?; - let status = match client.poll_login(attempt) { + let client = NativeClient::with_transport(options(), transport.clone())?; + let status = match client.poll_login_async(attempt).await { Ok(status) => status, Err(error) if wechat_protocol::is_retryable_login_poll_error(&error) => { - return Ok(json!({ "status": "retry" })) + return Ok(json!({ "status": "retry" })); } Err(error) => return Err(error), }; if status == LoginStatus::Approved { let mut attempt = session.attempt.take().expect("issued challenge"); - let state = client.complete_login(&mut attempt)?; + let state = client.complete_login_async(&mut attempt).await?; let result = json!({ "status": "completed", "username": state.own_username }); - session.account = Some(NativeClient::from_account(state, options())?); + session.account = Some(NativeClient::from_account_with_transport( + state, + options(), + transport, + )?); return Ok(result); } Ok(json!({ "status": status })) } Operation::Heartbeat => { - let beat = read_session(session, heartbeat)?; + let beat = read_session(session, async |session| heartbeat(session).await).await?; Ok( json!({ "sync": beat.selector & 7 != 0, "intervalMs": beat.next_interval.clamp(30, 180) * 1000 }), ) @@ -248,7 +159,7 @@ fn run(session: &mut Session, operation: Operation) -> Result { .incoming .as_mut() .context("No incoming connection")?; - match connection.poll(Duration::from_secs(1)) { + match connection.poll(Duration::from_secs(1)).await { Ok(notification) => Ok(json!( notification.is_some_and(|hint| hint.command == 24 && hint.selector & 7 != 0) )), @@ -257,22 +168,23 @@ fn run(session: &mut Session, operation: Operation) -> Result { // The notification socket closed. Reconnect and let one // heartbeat decide whether WeChat still accepts the session. session.incoming = None; - let beat = read_session(session, heartbeat)?; + let beat = + read_session(session, async |session| heartbeat(session).await).await?; Ok(json!(beat.selector & 7 != 0)) } } } - Operation::Sync { scene } => read_session(session, |session| sync(session, scene)), + Operation::Sync { scene } => { + read_session(session, async |session| sync(session, scene).await).await + } Operation::SendText { destination, text } => { + let transport = transport(session)?; let account = session .account .as_ref() .ok_or_else(|| anyhow!("No active session"))?; - let created_at = - u32::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs())?; - let mut random = [0; 4]; - openssl::rand::rand_bytes(&mut random)?; - let client_id = u32::from_le_bytes(random).max(1); + let created_at = transport.clock.unix_time_secs()?; + let client_id = u32::from_le_bytes(wechat_protocol::crypto::random::<4>()?).max(1); // Validate locally before the operation is allowed to reach transport. wire::text_send_request(&destination, &text, created_at, client_id)?; let send = TextSendOptions { @@ -280,42 +192,45 @@ fn run(session: &mut Session, operation: Operation) -> Result { client_message_id: client_id, source: None, }; - Ok(submit_once(|| { - account.request_blocking(|request| request.send_text(&destination, &text, &send)) - })) + Ok(submit_once( + account.send_text(&destination, &text, send).await, + )) } - Operation::LookupSelf => lookup_self(session), + Operation::LookupSelf => lookup_self(session).await, Operation::Logout => { session.incoming = None; let account = session.account.take().context("No active session")?; // Reserving the logout stops new account requests before submission. - let reply = account.prepare_logout()?.submit_blocking()?; + let reply = account.prepare_logout()?.submit().await?; Ok(json!({ "accepted": reply.accepted })) } Operation::Close => { if let Some(account) = session.account.take() { account.stop()?; } - *session = Session::default(); + *session = Session { + transport: session.transport.take(), + ..Default::default() + }; Ok(Value::Null) } } } -fn connection(session: &mut Session) -> Result<&mut AccountPushConnection> { +async fn connection(session: &mut Session) -> Result<&mut AsyncPushConnection> { if session.incoming.is_none() { let account = session.account.as_ref().context("No active session")?; - session.incoming = Some(account.open_push_connection_blocking()?); + session.incoming = Some(account.open_push_connection().await?); } session.incoming.as_mut().context("No incoming connection") } -fn heartbeat(session: &mut Session) -> Result { +async fn heartbeat(session: &mut Session) -> Result { let cursor = session.received_cursor.clone(); - connection(session)?.heartbeat(&cursor) + connection(session).await?.heartbeat(&cursor).await } -fn sync(session: &mut Session, scene: u32) -> Result { +async fn sync(session: &mut Session, scene: u32) -> Result { let own = session .account .as_ref() @@ -323,31 +238,29 @@ fn sync(session: &mut Session, scene: u32) -> Result { .account_identity()? .own_username; let cursor = session.received_cursor.clone(); - let batch = connection(session)?.sync(&cursor, scene)?; + let batch = connection(session).await?.sync(&cursor, scene).await?; let messages = text_messages(batch.commands, &own); session.received_cursor = batch.cursor; Ok(json!({ "messages": messages, "continuation": batch.continuation })) } /// Read-only session work. Sends never use this. -fn read_session( +async fn read_session( session: &mut Session, - operation: impl FnMut(&mut Session) -> Result, + operation: impl AsyncFnMut(&mut Session) -> Result, ) -> Result { recover( session, operation, - |session| { - session - .account - .as_ref() - .context("No active session")? - .renew_session_blocking(DEVICE_NAME) + async |session| { + let account = session.account.clone().context("No active session")?; + account.renew_session(DEVICE_NAME).await }, // A new socket is needed after a failure and after a renewal, because a // socket cannot adopt newer credentials. |session| session.incoming = None, ) + .await } /// Repeat read-only work after recovering from one socket failure and one @@ -356,16 +269,16 @@ fn read_session( /// phone can close the socket before any service code arrives. A rejection /// renews the credentials once, and a rejected renewal or a second rejection /// ends the session. Other service codes and a stopped account are returned. -fn recover( +async fn recover( session: &mut S, - mut operation: impl FnMut(&mut S) -> Result, - mut renew: impl FnMut(&mut S) -> Result<()>, + mut operation: impl AsyncFnMut(&mut S) -> Result, + mut renew: impl AsyncFnMut(&mut S) -> Result<()>, reconnect: impl Fn(&mut S), ) -> Result { let mut reconnected = false; let mut renewed = false; loop { - let error = match operation(session) { + let error = match operation(session).await { Ok(value) => return Ok(value), Err(error) => error, }; @@ -374,7 +287,7 @@ fn recover( return Err(error.context(SessionEnded)); } renewed = true; - if let Err(renewal) = renew(session) { + if let Err(renewal) = renew(session).await { return Err(if renewal_rejected(&renewal) { renewal.context(SessionEnded) } else { @@ -410,11 +323,10 @@ fn renewal_rejected(error: &anyhow::Error) -> bool { .is_some_and(|rejected| rejected.service == Service::AutomaticAuthentication) } -fn lookup_self(session: &mut Session) -> Result { +async fn lookup_self(session: &mut Session) -> Result { let account = session.account.as_ref().context("No active session")?; let own = account.account_identity()?.own_username; - let lookup = - account.request_blocking(|request| request.lookup_contacts(std::slice::from_ref(&own)))?; + let lookup = account.lookup_contacts(std::slice::from_ref(&own)).await?; let present = |value: Option| value.filter(|text| !text.is_empty()); let profile = lookup .contacts @@ -429,8 +341,9 @@ fn lookup_self(session: &mut Session) -> Result { Ok(json!(profile)) } -fn submit_once(send: impl FnOnce() -> Result) -> Value { - match send() { +/// The outcome of one send. A lost answer is uncertain, never retried. +fn submit_once(sent: Result) -> Value { + match sent { Ok(result) if result.accepted && result.returned_destination_matches @@ -451,70 +364,99 @@ fn submit_once(send: impl FnOnce() -> Result) -> Value { } } -fn text_messages(commands: Vec, username: &str) -> Vec { - commands - .into_iter() - .filter(|command| command.id == 5) - .filter_map(|command| wire::decode_add_message(&command.payload, username).ok()) - .filter_map(incoming_text) - .collect() -} +#[cfg(target_arch = "wasm32")] +mod exports { + use super::{Operation, Session, failure_message, host, run}; + use futures::lock::Mutex; + use js_sys::Promise; + use std::rc::Rc; + use wasm_bindgen::prelude::*; + use wasm_bindgen_futures::future_to_promise; + + /// One WeChat session. Operations run one at a time, in call order, and + /// resolve to JSON text. + #[wasm_bindgen] + pub struct NeoSession { + session: Rc>, + } + + #[wasm_bindgen] + impl NeoSession { + #[wasm_bindgen(constructor)] + pub fn new(host: host::NeoHost) -> Self { + Self { + session: Rc::new(Mutex::new(Session { + transport: Some(host::transport(host)), + ..Default::default() + })), + } + } -/// Incoming text with a server message ID. A group message names its member -/// sender in the content; one without a valid sender is skipped, never credited -/// to the group. -fn incoming_text(message: wire::AddMessage) -> Option { - if message.message_type != 1 || message.outgoing { - return None; - } - let (id, text) = (message.server_message_id?, message.content_text?); - let timestamp = message.created_at; - if message.from.ends_with("@chatroom") { - let (sender, body) = group_sender(&text)?; - Some(TextMessage { - id, - talker: sender.into(), - listener: None, - room: Some(message.from), - text: body.into(), - timestamp, - }) - } else { - Some(TextMessage { - id, - talker: message.from, - listener: Some(message.to), - room: None, - text, - timestamp, - }) + #[wasm_bindgen(js_name = startLogin)] + pub fn start_login(&self) -> Promise { + self.task(Operation::StartLogin) + } + + #[wasm_bindgen(js_name = pollLogin)] + pub fn poll_login(&self) -> Promise { + self.task(Operation::PollLogin) + } + + pub fn heartbeat(&self) -> Promise { + self.task(Operation::Heartbeat) + } + + pub fn sync(&self, scene: u32) -> Promise { + self.task(Operation::Sync { scene }) + } + + #[wasm_bindgen(js_name = pollIncoming)] + pub fn poll_incoming(&self) -> Promise { + self.task(Operation::PollIncoming) + } + + #[wasm_bindgen(js_name = sendText)] + pub fn send_text(&self, destination: String, text: String) -> Promise { + self.task(Operation::SendText { destination, text }) + } + + #[wasm_bindgen(js_name = lookupSelf)] + pub fn lookup_self(&self) -> Promise { + self.task(Operation::LookupSelf) + } + + pub fn logout(&self) -> Promise { + self.task(Operation::Logout) + } + + pub fn close(&self) -> Promise { + self.task(Operation::Close) + } } -} -/// Split group content into its sender and text. As in agent-wechat's daemon, -/// the sender is a plain identity of at most 512 bytes before the first `:\n`, -/// and never a group. -fn group_sender(text: &str) -> Option<(&str, &str)> { - let (sender, body) = text.split_once(":\n")?; - let valid = !sender.is_empty() - && sender.len() <= 512 - && !sender.chars().any(char::is_control) - && !sender.ends_with("@chatroom"); - valid.then_some((sender, body)) + impl NeoSession { + fn task(&self, operation: Operation) -> Promise { + let session = self.session.clone(); + future_to_promise(async move { + let stage = operation.stage(); + let mut session = session.lock().await; + match run(&mut session, operation).await { + Ok(output) => Ok(JsValue::from_str(&output.to_string())), + Err(error) => Err(js_sys::Error::new(&failure_message(stage, &error)).into()), + } + }) + } + } } #[cfg(test)] mod tests { use super::*; + use futures::executor::block_on; #[test] - fn lost_send_response_is_uncertain_after_one_attempt() { - let mut attempts = 0; - let result = submit_once(|| { - attempts += 1; - Err(anyhow!("lost acknowledgment")) - }); - assert_eq!(attempts, 1); + fn lost_send_response_is_uncertain() { + let result = submit_once(Err(anyhow!("lost acknowledgment"))); assert_eq!(result["status"], "uncertain"); } @@ -530,18 +472,18 @@ mod tests { let mut attempts = attempts.into_iter(); let mut renewal = Some(renewal); let mut steps = vec![]; - let result = recover( + let result = block_on(recover( &mut steps, - |steps| { + async |steps| { steps.push("attempt"); attempts.next().expect("an attempt was scripted") }, - |steps| { + async |steps| { steps.push("renew"); renewal.take().expect("one renewal was scripted") }, |steps| steps.push("reconnect"), - ); + )); (result, steps) } @@ -652,117 +594,19 @@ mod tests { assert!(!renewal_rejected(&anyhow!("connection reset"))); } - fn add_message(from: &str, to: &str, text: &str) -> wire::AddMessage { - wire::AddMessage { - from: from.into(), - to: to.into(), - peer: if to == "fixture-self" { from } else { to }.into(), - sender_id: (!from.ends_with("@chatroom")).then(|| from.into()), - outgoing: from == "fixture-self", - server_message_id: Some("fixture-message".into()), - numbered1: 0, - message_type: 1, - content: text.as_bytes().to_vec(), - content_text: Some(text.into()), - numbered6: 0, - numbered7: 0, - inline_data: vec![], - created_at: 1700000000, - msgsource: None, - opaque11: None, - numbered13: None, - server_sequence: None, - raw: vec![], - } - } - - #[test] - fn direct_and_group_text_name_the_talker() { - assert_eq!( - incoming_text(add_message("fixture-peer", "fixture-self", "ding")), - Some(TextMessage { - id: "fixture-message".into(), - talker: "fixture-peer".into(), - listener: Some("fixture-self".into()), - room: None, - text: "ding".into(), - timestamp: 1700000000, - }) - ); - assert_eq!( - incoming_text(add_message( - "fixture-room@chatroom", - "fixture-self", - "fixture-member:\nding" - )), - Some(TextMessage { - id: "fixture-message".into(), - talker: "fixture-member".into(), - listener: None, - room: Some("fixture-room@chatroom".into()), - text: "ding".into(), - timestamp: 1700000000, - }) - ); - let json = serde_json::to_value( - incoming_text(add_message( - "fixture-room@chatroom", - "fixture-self", - "fixture-member:\nline one\nline two", - )) - .unwrap(), - ) - .unwrap(); - assert_eq!(json["text"], "line one\nline two"); - assert!(json.get("listener").is_none()); - } - - #[test] - fn group_text_without_a_valid_sender_and_outgoing_text_are_skipped() { - let long = format!("{}:\nding", "a".repeat(513)); - for text in [ - "ding", - ":\nding", - "other-room@chatroom:\nding", - "bad\tsender:\nding", - long.as_str(), - ] { - assert_eq!( - incoming_text(add_message("fixture-room@chatroom", "fixture-self", text)), - None, - "{text:?}" - ); - } - assert_eq!( - incoming_text(add_message("fixture-self", "fixture-room@chatroom", "dong")), - None - ); - let mut image = add_message("fixture-peer", "fixture-self", ""); - image.message_type = 3; - assert_eq!(incoming_text(image), None); - } - #[test] fn closing_without_a_session_resets_state() { let mut session = Session { received_cursor: vec![1, 2, 3], ..Default::default() }; - assert_eq!(run(&mut session, Operation::Close).unwrap(), Value::Null); - assert!(session.received_cursor.is_empty()); - assert!(run(&mut session, Operation::LookupSelf).is_err()); - assert!(run(&mut session, Operation::Logout).is_err()); - } - - #[test] - fn unhandled_sync_commands_are_skipped() { - let messages = text_messages( - vec![wire::SyncCommand { - id: 9999, - payload: vec![42], - }], - "fixture-self", + assert_eq!( + block_on(run(&mut session, Operation::Close)).unwrap(), + Value::Null ); - assert!(messages.is_empty()); + assert!(session.received_cursor.is_empty()); + assert!(block_on(run(&mut session, Operation::LookupSelf)).is_err()); + assert!(block_on(run(&mut session, Operation::Logout)).is_err()); + assert!(block_on(run(&mut session, Operation::StartLogin)).is_err()); } } diff --git a/wasm/src/messages.rs b/wasm/src/messages.rs new file mode 100644 index 0000000..5bea898 --- /dev/null +++ b/wasm/src/messages.rs @@ -0,0 +1,177 @@ +use serde::Serialize; +use wechat_protocol::wire; + +#[derive(Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextMessage { + pub id: String, + /// Who wrote the message; in a group, the member who posted it. + pub talker: String, + /// The account that received a direct message. + #[serde(skip_serializing_if = "Option::is_none")] + pub listener: Option, + /// The group the message was posted in. + #[serde(skip_serializing_if = "Option::is_none")] + pub room: Option, + pub text: String, + pub timestamp: u32, +} + +pub fn text_messages(commands: Vec, username: &str) -> Vec { + commands + .into_iter() + .filter(|command| command.id == 5) + .filter_map(|command| wire::decode_add_message(&command.payload, username).ok()) + .filter_map(incoming_text) + .collect() +} + +/// Incoming text with a server message ID. A group message names its member +/// sender in the content; one without a valid sender is skipped, never credited +/// to the group. +fn incoming_text(message: wire::AddMessage) -> Option { + if message.message_type != 1 || message.outgoing { + return None; + } + let (id, text) = (message.server_message_id?, message.content_text?); + let timestamp = message.created_at; + if message.from.ends_with("@chatroom") { + let (sender, body) = group_sender(&text)?; + Some(TextMessage { + id, + talker: sender.into(), + listener: None, + room: Some(message.from), + text: body.into(), + timestamp, + }) + } else { + Some(TextMessage { + id, + talker: message.from, + listener: Some(message.to), + room: None, + text, + timestamp, + }) + } +} + +/// Split group content into its sender and text. As in agent-wechat's daemon, +/// the sender is a plain identity of at most 512 bytes before the first `:\n`, +/// and never a group. +fn group_sender(text: &str) -> Option<(&str, &str)> { + let (sender, body) = text.split_once(":\n")?; + let valid = !sender.is_empty() + && sender.len() <= 512 + && !sender.chars().any(char::is_control) + && !sender.ends_with("@chatroom"); + valid.then_some((sender, body)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn add_message(from: &str, to: &str, text: &str) -> wire::AddMessage { + wire::AddMessage { + from: from.into(), + to: to.into(), + peer: if to == "fixture-self" { from } else { to }.into(), + sender_id: (!from.ends_with("@chatroom")).then(|| from.into()), + outgoing: from == "fixture-self", + server_message_id: Some("fixture-message".into()), + numbered1: 0, + message_type: 1, + content: text.as_bytes().to_vec(), + content_text: Some(text.into()), + numbered6: 0, + numbered7: 0, + inline_data: vec![], + created_at: 1700000000, + msgsource: None, + opaque11: None, + numbered13: None, + server_sequence: None, + raw: vec![], + } + } + + #[test] + fn direct_and_group_text_name_the_talker() { + assert_eq!( + incoming_text(add_message("fixture-peer", "fixture-self", "ding")), + Some(TextMessage { + id: "fixture-message".into(), + talker: "fixture-peer".into(), + listener: Some("fixture-self".into()), + room: None, + text: "ding".into(), + timestamp: 1700000000, + }) + ); + assert_eq!( + incoming_text(add_message( + "fixture-room@chatroom", + "fixture-self", + "fixture-member:\nding" + )), + Some(TextMessage { + id: "fixture-message".into(), + talker: "fixture-member".into(), + listener: None, + room: Some("fixture-room@chatroom".into()), + text: "ding".into(), + timestamp: 1700000000, + }) + ); + let json = serde_json::to_value( + incoming_text(add_message( + "fixture-room@chatroom", + "fixture-self", + "fixture-member:\nline one\nline two", + )) + .unwrap(), + ) + .unwrap(); + assert_eq!(json["text"], "line one\nline two"); + assert!(json.get("listener").is_none()); + } + + #[test] + fn group_text_without_a_valid_sender_and_outgoing_text_are_skipped() { + let long = format!("{}:\nding", "a".repeat(513)); + for text in [ + "ding", + ":\nding", + "other-room@chatroom:\nding", + "bad\tsender:\nding", + long.as_str(), + ] { + assert_eq!( + incoming_text(add_message("fixture-room@chatroom", "fixture-self", text)), + None, + "{text:?}" + ); + } + assert_eq!( + incoming_text(add_message("fixture-self", "fixture-room@chatroom", "dong")), + None + ); + let mut image = add_message("fixture-peer", "fixture-self", ""); + image.message_type = 3; + assert_eq!(incoming_text(image), None); + } + + #[test] + fn unhandled_sync_commands_are_skipped() { + let messages = text_messages( + vec![wire::SyncCommand { + id: 9999, + payload: vec![42], + }], + "fixture-self", + ); + assert!(messages.is_empty()); + } +}