From f94b67cdb4548274787f8bd58dc6c61a37567ec8 Mon Sep 17 00:00:00 2001 From: Sheng Kun Chang Date: Thu, 30 Apr 2026 13:38:20 +0800 Subject: [PATCH 1/6] chore!: rewrite mirrorstack-cli in Rust MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces the entire Go codebase with a clap-based Rust implementation. Same surface area (login + app module init), same OAuth contract against api-platform. Why: prefer Rust for the CLI's distribution story (smaller statically linked binary, polished release tooling) and per-platform OS handler registration story for the upcoming custom-scheme work (#7). Crates: - clap (derive) for arg parsing — no more hand-rolled switch dispatch - reqwest (blocking, rustls) for HTTP — avoids OpenSSL on macOS - serde + serde_json — token response decoding - sha2 + base64 + rand — PKCE generation - dirs — cross-platform config_dir - tempfile — atomic credentials write - open — best-effort browser launcher - thiserror + anyhow — typed library errors + application errors Modules: - src/auth/ OAuth 2.0 + PKCE client (port of internal/auth) - src/credentials/ Atomic 0600 token persistence (port of internal/credentials) - src/browser.rs Cross-platform URL opener (port of internal/browser) - src/scaffold/ Module scaffold + validation + templates (port of scaffold/) - src/commands/ Subcommand modules (login, app) Tests: - 14 cargo tests cover PKCE generation, AuthorizeURL shape, token exchange happy + 4 typed sentinels (invalid_grant / invalid_request / invalid_client / unsupported_grant_type) + 5xx ErrServerError + unknown OAuth code, credentials roundtrip + 0600 mode + ErrNotFound, scaffold name validation + to_title transformations. Release binary is 3.2MB stripped (was ~6MB for the Go version). Closes #5. Co-Authored-By: Claude Opus 4.7 (1M context) --- .gitignore | 2 +- Cargo.lock | 2128 +++++++++++++++++++++++++++++++++++++ Cargo.toml | 34 + README.md | 31 +- cmd/init.go | 29 - cmd/root.go | 87 -- go.mod | 3 - main.go | 15 - scaffold/scaffold.go | 57 - scaffold/templates.go | 253 ----- scaffold/validate.go | 22 - src/auth/mod.rs | 167 +++ src/auth/tests.rs | 157 +++ src/browser.rs | 9 + src/commands/app.rs | 41 + src/commands/login.rs | 85 ++ src/commands/mod.rs | 33 + src/credentials/mod.rs | 101 ++ src/credentials/tests.rs | 61 ++ src/main.rs | 23 + src/scaffold/mod.rs | 69 ++ src/scaffold/templates.rs | 260 +++++ src/scaffold/validate.rs | 51 + 23 files changed, 3246 insertions(+), 472 deletions(-) create mode 100644 Cargo.lock create mode 100644 Cargo.toml delete mode 100644 cmd/init.go delete mode 100644 cmd/root.go delete mode 100644 go.mod delete mode 100644 main.go delete mode 100644 scaffold/scaffold.go delete mode 100644 scaffold/templates.go delete mode 100644 scaffold/validate.go create mode 100644 src/auth/mod.rs create mode 100644 src/auth/tests.rs create mode 100644 src/browser.rs create mode 100644 src/commands/app.rs create mode 100644 src/commands/login.rs create mode 100644 src/commands/mod.rs create mode 100644 src/credentials/mod.rs create mode 100644 src/credentials/tests.rs create mode 100644 src/main.rs create mode 100644 src/scaffold/mod.rs create mode 100644 src/scaffold/templates.rs create mode 100644 src/scaffold/validate.rs diff --git a/.gitignore b/.gitignore index 007982f..b52a2cc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ .DS_Store -mirrorstack-cli +/target dist/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..07fa36b --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2128 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + +[[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 = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "colored" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[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 = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "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", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "h2" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", + "serde", + "serde_core", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1840c94c045fbcf8ba2812c95db44499f7c64910a912551aaaa541decebcacf" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libredox" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "mirrorstack" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64", + "clap", + "dirs", + "mockito", + "open", + "rand", + "reqwest", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror", + "url", +] + +[[package]] +name = "mockito" +version = "1.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90820618712cab19cfc46b274c6c22546a82affcb3c3bdf0f29e3db8e1bb92c0" +dependencies = [ + "assert-json-diff", + "bytes", + "colored", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "log", + "pin-project-lite", + "rand", + "regex", + "serde_json", + "serde_urlencoded", + "similar", + "tokio", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "open" +version = "5.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f3bab717c29a857abf75fcef718d441ec7cb2725f937343c734740a985d37fd" +dependencies = [ + "is-wsl", + "libc", + "pathdiff", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pathdiff" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +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 = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen 0.46.0", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df52b6d9b87e0c74c9edfa1eb2d9bf85e5d63515474513aa50fa181b3c4f5db1" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.70" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af934872acec734c2d80e6617bbb5ff4f12b052dd8e6332b0817bce889516084" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b1041f495fb322e64aca85f5756b2172e35cd459376e67f2a6c9dffcedb103" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dcd0ff20416988a18ac686d4d4d0f6aae9ebf08a389ff5d29012b05af2a1b41" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49757b3c82ebf16c57d69365a142940b384176c24df52a087fb748e2085359ea" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eadbac71025cd7b0834f20d1fe8472e8495821b4e9801eb0a60bd1f19827602" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e04ffcb --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "mirrorstack" +version = "0.1.0" +edition = "2024" +rust-version = "1.85" +description = "Official command-line tool for the MirrorStack platform" +license = "Apache-2.0" + +[[bin]] +name = "mirrorstack" +path = "src/main.rs" + +[dependencies] +clap = { version = "4.5", features = ["derive"] } +reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls", "json"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +base64 = "0.22" +rand = "0.9" +url = "2" +dirs = "6" +open = "5" +anyhow = "1" +thiserror = "2" +tempfile = "3" + +[dev-dependencies] +mockito = "1.6" + +[profile.release] +strip = true +lto = "thin" +codegen-units = 1 diff --git a/README.md b/README.md index 57cfcb5..c68a62f 100644 --- a/README.md +++ b/README.md @@ -5,21 +5,42 @@ Scaffold, develop, and deploy MirrorStack modules. ## Install ```bash -go install github.com/mirrorstack-ai/mirrorstack-cli@latest +cargo install --git https://github.com/mirrorstack-ai/mirrorstack-cli ``` +Pre-built releases (brew, scoop, deb) coming with the next milestone. + ## Commands ```bash -mirrorstack app module init # Scaffold a new module -mirrorstack version # Show CLI version -mirrorstack help # Show help +mirrorstack login # Sign in via OAuth (PKCE) +mirrorstack app module init # Scaffold a new module +mirrorstack --help # Show help +mirrorstack --version # Show CLI version ``` -## Quick Start +## Quick start ```bash +mirrorstack login mirrorstack app module init my-module cd my-module # Edit api/, web/, sql/ as needed ``` + +## Local development + +Build: + +```bash +cargo build +cargo test +``` + +Run against local services: + +```bash +MIRRORSTACK_API_URL=http://localhost:8081 \ +MIRRORSTACK_WEB_URL=http://localhost:3000 \ +cargo run -- login +``` diff --git a/cmd/init.go b/cmd/init.go deleted file mode 100644 index 2b6977d..0000000 --- a/cmd/init.go +++ /dev/null @@ -1,29 +0,0 @@ -package cmd - -import ( - "fmt" - - "github.com/mirrorstack-ai/mirrorstack-cli/scaffold" -) - -func runInit(args []string) error { - if len(args) == 0 { - return fmt.Errorf("usage: mirrorstack app module init ") - } - - name := args[0] - if err := scaffold.Validate(name); err != nil { - return err - } - - fmt.Printf("Creating module: %s\n\n", name) - - if err := scaffold.Create(name); err != nil { - return err - } - - fmt.Printf("\nDone! Next steps:\n") - fmt.Printf(" cd %s\n", name) - fmt.Printf(" mirrorstack dev\n") - return nil -} diff --git a/cmd/root.go b/cmd/root.go deleted file mode 100644 index 4df0691..0000000 --- a/cmd/root.go +++ /dev/null @@ -1,87 +0,0 @@ -package cmd - -import "fmt" - -const version = "0.1.0" - -func Run(args []string) error { - if len(args) == 0 { - printUsage() - return nil - } - - switch args[0] { - case "app": - return runApp(args[1:]) - case "version", "--version", "-v": - fmt.Println("mirrorstack", version) - return nil - case "help", "--help", "-h": - printUsage() - return nil - default: - return fmt.Errorf("unknown command: %s\nRun 'mirrorstack help' for usage", args[0]) - } -} - -func runApp(args []string) error { - if len(args) == 0 { - printAppUsage() - return nil - } - - switch args[0] { - case "module": - return runAppModule(args[1:]) - case "help", "--help", "-h": - printAppUsage() - return nil - default: - return fmt.Errorf("unknown command: mirrorstack app %s\nRun 'mirrorstack app help' for usage", args[0]) - } -} - -func runAppModule(args []string) error { - if len(args) == 0 { - printAppModuleUsage() - return nil - } - - switch args[0] { - case "init": - return runInit(args[1:]) - case "help", "--help", "-h": - printAppModuleUsage() - return nil - default: - return fmt.Errorf("unknown command: mirrorstack app module %s\nRun 'mirrorstack app module help' for usage", args[0]) - } -} - -func printUsage() { - fmt.Println(`MirrorStack CLI - -Usage: - mirrorstack - -Commands: - app App and module management - version Show CLI version - help Show this help`) -} - -func printAppUsage() { - fmt.Println(`Usage: - mirrorstack app - -Commands: - module Module management`) -} - -func printAppModuleUsage() { - fmt.Println(`Usage: - mirrorstack app module - -Commands: - init Scaffold a new module`) -} diff --git a/go.mod b/go.mod deleted file mode 100644 index 4d48fdb..0000000 --- a/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/mirrorstack-ai/mirrorstack-cli - -go 1.24 diff --git a/main.go b/main.go deleted file mode 100644 index 93aa5bb..0000000 --- a/main.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - "os" - - "github.com/mirrorstack-ai/mirrorstack-cli/cmd" -) - -func main() { - if err := cmd.Run(os.Args[1:]); err != nil { - fmt.Fprintln(os.Stderr, "error:", err) - os.Exit(1) - } -} diff --git a/scaffold/scaffold.go b/scaffold/scaffold.go deleted file mode 100644 index a23d37d..0000000 --- a/scaffold/scaffold.go +++ /dev/null @@ -1,57 +0,0 @@ -package scaffold - -import ( - "fmt" - "os" - "path/filepath" - "strings" -) - -func Create(name string) error { - title := toTitle(name) - - files := map[string]string{ - "mirrorstack.yaml": mirrorstackYAML(name, title), - "MIRRORSTACK.md": mirrorstackMD(name, title), - ".gitignore": gitignore(), - "sql/0000_initial.up.sql": initialUpSQL(), - "sql/0000_initial.down.sql": initialDownSQL(), - "api/go.mod": goMod(name), - "api/module.go": moduleGo(name, title), - "api/cmd/main.go": cmdMainGo(name), - "api/handler/public.go": handlerPublicGo(name), - "api/handler/admin.go": handlerAdminGo(name), - "api/service/" + name + ".go": serviceGo(name), - "api/db/sqlc.yaml": sqlcYAML(name), - "api/db/queries/" + name + ".sql": queriesSQL(name), - "web/package.json": webPackageJSON(name), - "web/platform/index.ts": webPlatformIndex(title), - "web/platform/pages/" + title + "Page.tsx": webPlatformPage(title), - "web/app/index.ts": webAppIndex(title), - "web/app/pages/" + title + "Page.tsx": webAppPage(title), - } - - for path, content := range files { - fullPath := filepath.Join(name, path) - dir := filepath.Dir(fullPath) - if err := os.MkdirAll(dir, 0o755); err != nil { - return fmt.Errorf("create dir %s: %w", dir, err) - } - if err := os.WriteFile(fullPath, []byte(content), 0o644); err != nil { - return fmt.Errorf("write %s: %w", fullPath, err) - } - fmt.Printf(" created %s\n", path) - } - - return nil -} - -func toTitle(name string) string { - parts := strings.Split(name, "-") - for i, p := range parts { - if len(p) > 0 { - parts[i] = strings.ToUpper(p[:1]) + p[1:] - } - } - return strings.Join(parts, "") -} diff --git a/scaffold/templates.go b/scaffold/templates.go deleted file mode 100644 index 3fd81d7..0000000 --- a/scaffold/templates.go +++ /dev/null @@ -1,253 +0,0 @@ -package scaffold - -import "fmt" - -func mirrorstackYAML(name, title string) string { - return fmt.Sprintf(`id: %s -name: %s -description: "" -icon: extension -category: content -version: "0.1.0" - -dependencies: [] -optional_dependencies: [] - -platform: - nav_items: - - icon: extension - label: %s - route: /%s - - pages: - - route: /%s - component: %sPage - -app: - pages: - - route: /%s - component: %sPage -`, name, title, title, name, name, title, name, title) -} - -func mirrorstackMD(name, title string) string { - return fmt.Sprintf(`# %s Module - -TODO: Describe what this module does. - -## Capabilities -- TODO - -## When to use -- TODO - -## Data model -- TODO - -## Relationships -- Depends on: TODO -`, title) -} - -func gitignore() string { - return `.DS_Store -api/bootstrap -api/lambda.zip -web/dist/ -web/node_modules/ -` -} - -func initialUpSQL() string { - return `-- Create your tables here --- This runs inside each app's schema (search_path is set automatically) - --- CREATE TABLE items ( --- id UUID PRIMARY KEY DEFAULT gen_random_uuid(), --- title TEXT NOT NULL, --- created_at TIMESTAMPTZ NOT NULL DEFAULT now() --- ); -` -} - -func initialDownSQL() string { - return `-- Reverse of 0000_initial.up.sql - --- DROP TABLE IF EXISTS items; -` -} - -func goMod(name string) string { - return fmt.Sprintf(`module github.com/mirrorstack-ai/app-mod-%s - -go 1.24 - -// require github.com/mirrorstack-ai/app-module-sdk v0.1.0 -`, name) -} - -func moduleGo(name, title string) string { - return fmt.Sprintf(`package %s - -import ( - "github.com/go-chi/chi/v5" - // modulesdk "github.com/mirrorstack-ai/app-module-sdk" -) - -type Module struct { - // pool *pgxpool.Pool -} - -func New() *Module { - return &Module{} -} - -func (m *Module) ID() string { - return "%s" -} - -func (m *Module) Routes(r chi.Router) { - // TODO: mount handlers -} -`, name, name) -} - -func cmdMainGo(name string) string { - return fmt.Sprintf(`package main - -import ( - "fmt" - "net/http" - "os" - - "github.com/go-chi/chi/v5" - // modulesdk "github.com/mirrorstack-ai/app-module-sdk" - // "%s" module package -) - -func main() { - r := chi.NewRouter() - // r.Use(modulesdk.ExtractContext) - - r.Get("/health", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("ok")) - }) - - // mod := %s.New() - // mod.Routes(r) - - port := os.Getenv("PORT") - if port == "" { - port = "8080" - } - - fmt.Printf("listening on :%%s\n", port) - http.ListenAndServe(":"+port, r) -} -`, name, name) -} - -func handlerPublicGo(name string) string { - return fmt.Sprintf(`package handler - -// Public handlers — end user routes (requires app user JWT) - -type Handler struct { - // service *service.%sService -} - -func New() *Handler { - return &Handler{} -} -`, toTitle(name)) -} - -func handlerAdminGo(name string) string { - return `package handler - -// Admin handlers — app owner routes (requires app user JWT + admin role) -` -} - -func serviceGo(name string) string { - return fmt.Sprintf(`package service - -type %sService struct { - // pool *pgxpool.Pool -} - -func New() *%sService { - return &%sService{} -} -`, toTitle(name), toTitle(name), toTitle(name)) -} - -func sqlcYAML(name string) string { - return fmt.Sprintf(`version: "2" -sql: - - engine: "postgresql" - queries: "queries/" - schema: "../../sql/*.up.sql" - gen: - go: - package: "generated" - out: "generated" - sql_package: "pgx/v5" - emit_json_tags: true - overrides: - - db_type: "uuid" - go_type: "github.com/jackc/pgx/v5/pgtype.UUID" - - db_type: "timestamptz" - go_type: "github.com/jackc/pgx/v5/pgtype.Timestamptz" -`) -} - -func queriesSQL(name string) string { - return fmt.Sprintf(`-- name: List%s :many --- SELECT * FROM items ORDER BY created_at DESC LIMIT $1 OFFSET $2; -`, toTitle(name)) -} - -func webPackageJSON(name string) string { - return fmt.Sprintf(`{ - "name": "@mirrorstack-ai/mod-%s-web", - "version": "0.1.0", - "private": true, - "type": "module" -} -`, name) -} - -func webPlatformIndex(title string) string { - return fmt.Sprintf(`export { %sPage } from "./pages/%sPage"; -`, title, title) -} - -func webPlatformPage(title string) string { - return fmt.Sprintf(`export function %sPage() { - return ( -
-

%s

-

Platform dashboard page

-
- ); -} -`, title, title) -} - -func webAppIndex(title string) string { - return fmt.Sprintf(`export { %sPage } from "./pages/%sPage"; -`, title, title) -} - -func webAppPage(title string) string { - return fmt.Sprintf(`export function %sPage() { - return ( -
-

%s

-

App page

-
- ); -} -`, title, title) -} diff --git a/scaffold/validate.go b/scaffold/validate.go deleted file mode 100644 index aa574f8..0000000 --- a/scaffold/validate.go +++ /dev/null @@ -1,22 +0,0 @@ -package scaffold - -import ( - "fmt" - "os" - "regexp" -) - -var validID = regexp.MustCompile(`^[a-z][a-z0-9-]*$`) - -func Validate(name string) error { - if len(name) < 2 || len(name) > 40 { - return fmt.Errorf("module name must be 2-40 characters, got %d", len(name)) - } - if !validID.MatchString(name) { - return fmt.Errorf("module name must be lowercase alphanumeric with hyphens (e.g., my-analytics)") - } - if _, err := os.Stat(name); err == nil { - return fmt.Errorf("directory %q already exists", name) - } - return nil -} diff --git a/src/auth/mod.rs b/src/auth/mod.rs new file mode 100644 index 0000000..ba29369 --- /dev/null +++ b/src/auth/mod.rs @@ -0,0 +1,167 @@ +//! OAuth 2.0 authorization-code + PKCE client. Pairs with api-platform's +//! `/v1/oauth/*` endpoints and the web-account `/authorize` consent page. +//! +//! OOB delivery (`urn:ietf:wg:oauth:2.0:oob`): the user pastes the code +//! displayed on the consent page back into the terminal. Custom-scheme +//! and per-OS handler registration is the follow-up tracked at #7. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use rand::TryRngCore; +use rand::rngs::OsRng; +use reqwest::blocking::Client; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use thiserror::Error; +use url::Url; + +/// Identifies the CLI to the platform; matches the seed in +/// api-platform migration `011_oauth.up.sql`. +pub const CLIENT_ID: &str = "mirrorstack-cli"; + +/// RFC 6749 §1.3.1 OOB sentinel — used while custom-scheme delivery is +/// not yet shipped (mirrorstack-cli#7). +pub const REDIRECT_URI: &str = "urn:ietf:wg:oauth:2.0:oob"; + +/// PKCE method the platform accepts. RFC 7636 §4.3. +const CHALLENGE_METHOD: &str = "S256"; + +#[derive(Debug, Clone)] +pub struct Pkce { + pub verifier: String, + pub challenge: String, +} + +impl Pkce { + /// 32 random bytes encoded base64url-no-pad → SHA256 → base64url-no-pad. + pub fn generate() -> Result { + let verifier = random_b64url(32)?; + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + Ok(Self { verifier, challenge }) + } +} + +/// Build the consent-page URL the user opens in a browser. +pub fn authorize_url(web_base: &str, state: &str, pkce: &Pkce) -> String { + let base = web_base.trim_end_matches('/'); + let mut u = Url::parse(&format!("{base}/authorize")) + .unwrap_or_else(|_| Url::parse("https://account.mirrorstack.ai/authorize").unwrap()); + u.query_pairs_mut() + .append_pair("client_id", CLIENT_ID) + .append_pair("redirect_uri", REDIRECT_URI) + .append_pair("response_type", "code") + .append_pair("code_challenge", &pkce.challenge) + .append_pair("code_challenge_method", CHALLENGE_METHOD) + .append_pair("state", state); + u.into() +} + +/// 16 random bytes, base64url-no-pad. State is required by the auth +/// server but not validated end-to-end in OOB (paste only carries the +/// code). Generalizes when custom-scheme delivery lands. +pub fn random_state() -> Result { + random_b64url(16) +} + +/// RFC 6749 §5.1 token endpoint success body. MirrorStack returns the +/// opaque refresh_token in the body for non-cookie callers like CLIs. +#[derive(Debug, Deserialize)] +#[allow(dead_code)] // token_type is read by serde but not branched on +pub struct TokenResponse { + pub access_token: String, + #[serde(default)] + pub token_type: String, + pub expires_in: i64, + pub refresh_token: String, +} + +/// Exchange the pasted auth code (+ PKCE verifier) for tokens. +pub fn exchange_code( + http: &Client, + api_base: &str, + code: &str, + pkce: &Pkce, +) -> Result { + let endpoint = format!("{}/v1/oauth/token", api_base.trim_end_matches('/')); + let form = [ + ("grant_type", "authorization_code"), + ("client_id", CLIENT_ID), + ("code", code), + ("code_verifier", &pkce.verifier), + ("redirect_uri", REDIRECT_URI), + ]; + + let resp = http + .post(&endpoint) + .header("Accept", "application/json") + .form(&form) + .send() + .map_err(AuthError::Http)?; + + let status = resp.status(); + let body = resp.text().map_err(AuthError::Http)?; + + if status.is_success() { + return serde_json::from_str(&body).map_err(|e| AuthError::Decode(e.to_string())); + } + + // RFC 6749 §5.2 error body — map known codes to typed sentinels. + let parsed: ErrorBody = serde_json::from_str(&body).unwrap_or_default(); + match parsed.error.as_deref() { + Some("invalid_grant") => Err(AuthError::InvalidGrant), + Some("invalid_request") => Err(AuthError::InvalidRequest), + Some("invalid_client") => Err(AuthError::InvalidClient), + Some("unsupported_grant_type") => Err(AuthError::UnsupportedGrant), + _ if status.is_server_error() => Err(AuthError::Server { + status: status.as_u16(), + description: parsed.error_description.unwrap_or_default(), + }), + Some(code) => Err(AuthError::Other { + code: code.to_string(), + description: parsed.error_description.unwrap_or_default(), + }), + None => Err(AuthError::Unexpected { + status: status.as_u16(), + body, + }), + } +} + +#[derive(Debug, Error)] +pub enum AuthError { + #[error("auth: code is invalid, expired, or already used")] + InvalidGrant, + #[error("auth: malformed token request")] + InvalidRequest, + #[error("auth: client authentication failed")] + InvalidClient, + #[error("auth: grant_type not supported")] + UnsupportedGrant, + #[error("auth: server error ({status}): {description}")] + Server { status: u16, description: String }, + #[error("auth: {code}: {description}")] + Other { code: String, description: String }, + #[error("auth: unexpected response {status}: {body}")] + Unexpected { status: u16, body: String }, + #[error("auth: HTTP error: {0}")] + Http(#[source] reqwest::Error), + #[error("auth: decode response: {0}")] + Decode(String), + #[error("auth: random source: {0}")] + Random(#[source] rand::rand_core::OsError), +} + +#[derive(Debug, Default, Deserialize)] +struct ErrorBody { + error: Option, + error_description: Option, +} + +fn random_b64url(n: usize) -> Result { + let mut buf = vec![0u8; n]; + OsRng.try_fill_bytes(&mut buf).map_err(AuthError::Random)?; + Ok(URL_SAFE_NO_PAD.encode(buf)) +} + +#[cfg(test)] +mod tests; diff --git a/src/auth/tests.rs b/src/auth/tests.rs new file mode 100644 index 0000000..996220b --- /dev/null +++ b/src/auth/tests.rs @@ -0,0 +1,157 @@ +use super::*; + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use sha2::{Digest, Sha256}; + +#[test] +fn pkce_challenge_matches_sha256_of_verifier() { + let p = Pkce::generate().expect("generate"); + let want = URL_SAFE_NO_PAD.encode(Sha256::digest(p.verifier.as_bytes())); + assert_eq!(p.challenge, want); +} + +#[test] +fn pkce_unique_across_calls() { + let mut seen = std::collections::HashSet::new(); + for _ in 0..50 { + let p = Pkce::generate().expect("generate"); + assert!(seen.insert(p.verifier), "duplicate verifier"); + } +} + +#[test] +fn authorize_url_carries_required_params() { + let p = Pkce { verifier: "v".into(), challenge: "abc".into() }; + let raw = authorize_url("https://example.com", "STATE", &p); + let u = url::Url::parse(&raw).expect("parse"); + assert_eq!(u.path(), "/authorize"); + + let q: std::collections::HashMap<_, _> = u.query_pairs().into_owned().collect(); + assert_eq!(q.get("client_id").map(String::as_str), Some(CLIENT_ID)); + assert_eq!(q.get("redirect_uri").map(String::as_str), Some(REDIRECT_URI)); + assert_eq!(q.get("response_type").map(String::as_str), Some("code")); + assert_eq!(q.get("code_challenge").map(String::as_str), Some("abc")); + assert_eq!(q.get("code_challenge_method").map(String::as_str), Some("S256")); + assert_eq!(q.get("state").map(String::as_str), Some("STATE")); +} + +#[test] +fn authorize_url_trims_trailing_slash() { + let p = Pkce { verifier: "v".into(), challenge: "c".into() }; + let raw = authorize_url("https://example.com/", "s", &p); + assert!( + raw.starts_with("https://example.com/authorize?"), + "got {raw}" + ); +} + +mod exchange { + use super::*; + + use mockito::{Matcher, Server}; + use reqwest::blocking::Client; + use serde_json::json; + use std::time::Duration; + + fn http() -> Client { + Client::builder() + .timeout(Duration::from_secs(5)) + .build() + .unwrap() + } + + #[test] + fn success_returns_tokens() { + let mut server = Server::new(); + let m = server + .mock("POST", "/v1/oauth/token") + .match_header("accept", "application/json") + .match_body(Matcher::AllOf(vec![ + Matcher::UrlEncoded("grant_type".into(), "authorization_code".into()), + Matcher::UrlEncoded("code".into(), "AUTHCODE".into()), + Matcher::UrlEncoded("code_verifier".into(), "VERIFIER".into()), + ])) + .with_status(200) + .with_body( + json!({"access_token":"AT","token_type":"Bearer","expires_in":900,"refresh_token":"RT"}) + .to_string(), + ) + .create(); + + let pkce = Pkce { verifier: "VERIFIER".into(), challenge: "C".into() }; + let tr = exchange_code(&http(), &server.url(), "AUTHCODE", &pkce).expect("ok"); + m.assert(); + assert_eq!(tr.access_token, "AT"); + assert_eq!(tr.refresh_token, "RT"); + assert_eq!(tr.expires_in, 900); + } + + #[test] + fn typed_sentinels() { + for (oauth_code, want_match) in [ + ("invalid_grant", "InvalidGrant"), + ("invalid_request", "InvalidRequest"), + ("invalid_client", "InvalidClient"), + ("unsupported_grant_type", "UnsupportedGrant"), + ] { + let mut server = Server::new(); + let _m = server + .mock("POST", "/v1/oauth/token") + .with_status(400) + .with_body(json!({"error": oauth_code, "error_description": "x"}).to_string()) + .create(); + + let err = exchange_code( + &http(), + &server.url(), + "X", + &Pkce { verifier: "v".into(), challenge: "c".into() }, + ) + .unwrap_err(); + let actual = format!("{err:?}"); + assert!( + actual.contains(want_match), + "for {oauth_code}: got {actual}, want {want_match}" + ); + } + } + + #[test] + fn server_5xx_is_typed() { + let mut server = Server::new(); + let _m = server + .mock("POST", "/v1/oauth/token") + .with_status(503) + .with_body(json!({"error":"server_error","error_description":"boom"}).to_string()) + .create(); + + let err = exchange_code( + &http(), + &server.url(), + "X", + &Pkce { verifier: "v".into(), challenge: "c".into() }, + ) + .unwrap_err(); + assert!(matches!(err, AuthError::Server { .. }), "got {err:?}"); + } + + #[test] + fn unknown_oauth_code_is_other() { + let mut server = Server::new(); + let _m = server + .mock("POST", "/v1/oauth/token") + .with_status(400) + .with_body(json!({"error":"made_up","error_description":"x"}).to_string()) + .create(); + + let err = exchange_code( + &http(), + &server.url(), + "X", + &Pkce { verifier: "v".into(), challenge: "c".into() }, + ) + .unwrap_err(); + assert!(matches!(err, AuthError::Other { ref code, .. } if code == "made_up"), "got {err:?}"); + } +} diff --git a/src/browser.rs b/src/browser.rs new file mode 100644 index 0000000..61ad999 --- /dev/null +++ b/src/browser.rs @@ -0,0 +1,9 @@ +//! Best-effort browser opener. Callers should always print the URL +//! alongside calling [`open`] so the user can copy-paste if auto-open +//! fails (headless env, SSH, browser crashed, etc.). + +use std::io; + +pub fn open(url: &str) -> io::Result<()> { + ::open::that(url) +} diff --git a/src/commands/app.rs b/src/commands/app.rs new file mode 100644 index 0000000..05a007c --- /dev/null +++ b/src/commands/app.rs @@ -0,0 +1,41 @@ +//! `mirrorstack app ...` — app and module management commands. + +use anyhow::Result; +use clap::{Args, Subcommand}; + +use crate::scaffold; + +#[derive(Args)] +pub struct AppArgs { + #[command(subcommand)] + command: AppCommand, +} + +#[derive(Subcommand)] +enum AppCommand { + /// Module management. + Module(ModuleArgs), +} + +#[derive(Args)] +struct ModuleArgs { + #[command(subcommand)] + command: ModuleCommand, +} + +#[derive(Subcommand)] +enum ModuleCommand { + /// Scaffold a new module in the current directory. + Init { + /// Module name (lowercase alphanumeric + hyphens, 2-40 chars). + name: String, + }, +} + +pub fn run(args: AppArgs) -> Result<()> { + match args.command { + AppCommand::Module(m) => match m.command { + ModuleCommand::Init { name } => scaffold::run_init(&name), + }, + } +} diff --git a/src/commands/login.rs b/src/commands/login.rs new file mode 100644 index 0000000..ea68e8c --- /dev/null +++ b/src/commands/login.rs @@ -0,0 +1,85 @@ +//! `mirrorstack login` — drives the OAuth 2.0 authorization-code+PKCE +//! flow against api-platform's `/v1/oauth/*` endpoints. +//! +//! Today this is OOB-only: the consent page displays the auth code, the +//! user pastes it into the terminal, and the CLI exchanges code+verifier +//! for tokens. Custom-scheme delivery is the follow-up tracked at +//! mirrorstack-cli#7. + +use std::io::{self, BufRead, Write}; +use std::time::{Duration, SystemTime}; + +use anyhow::{Context, Result, anyhow}; +use clap::Args; +use reqwest::blocking::Client; + +use crate::auth::{self, AuthError}; +use crate::browser; +use crate::credentials::{self, Credentials}; + +const DEFAULT_API_BASE: &str = "https://api.mirrorstack.ai"; +const DEFAULT_WEB_BASE: &str = "https://account.mirrorstack.ai"; +const ENV_API_URL: &str = "MIRRORSTACK_API_URL"; +const ENV_WEB_URL: &str = "MIRRORSTACK_WEB_URL"; + +#[derive(Args)] +pub struct LoginArgs {} + +pub fn run(_args: LoginArgs) -> Result<()> { + let api_base = std::env::var(ENV_API_URL).unwrap_or_else(|_| DEFAULT_API_BASE.into()); + let web_base = std::env::var(ENV_WEB_URL).unwrap_or_else(|_| DEFAULT_WEB_BASE.into()); + + let pkce = auth::Pkce::generate()?; + let state = auth::random_state()?; + let authorize_url = auth::authorize_url(&web_base, &state, &pkce); + + println!("Opening your browser to sign in:\n"); + println!(" {authorize_url}\n"); + if browser::open(&authorize_url).is_err() { + eprintln!("(could not auto-open browser; copy the URL above and paste it manually)"); + } + + print!("After approving in the browser, paste the code here: "); + io::stdout().flush().ok(); + let code = read_line(io::stdin().lock())?; + let code = code.trim(); + if code.is_empty() { + return Err(anyhow!("login: no code entered")); + } + + let http = Client::builder() + .timeout(Duration::from_secs(30)) + .build() + .context("login: build HTTP client")?; + + let tokens = match auth::exchange_code(&http, &api_base, code, &pkce) { + Ok(t) => t, + Err(AuthError::InvalidGrant) => { + return Err(anyhow!( + "login: code didn't work — it may have expired or already been used. \ + Run `mirrorstack login` again to get a fresh one." + )); + } + Err(e) => return Err(e.into()), + }; + + let creds = Credentials { + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + expires_at: SystemTime::now() + Duration::from_secs(tokens.expires_in.max(0) as u64), + }; + credentials::save(&creds)?; + + let path = credentials::path()?; + println!("\nSigned in. Tokens saved to {}", path.display()); + Ok(()) +} + +fn read_line(mut r: R) -> Result { + let mut buf = String::new(); + let n = r.read_line(&mut buf).context("read input")?; + if n == 0 { + return Err(anyhow!("read input: end of input (no code provided)")); + } + Ok(buf) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000..bd6c572 --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,33 @@ +//! Top-level CLI surface. Each variant of `Command` maps to a subcommand +//! module under this directory. + +use anyhow::Result; +use clap::{Parser, Subcommand}; + +mod app; +mod login; + +/// Official command-line tool for the MirrorStack platform. +#[derive(Parser)] +#[command(name = "mirrorstack", version, about, long_about = None)] +pub struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Sign in to MirrorStack via OAuth. + Login(login::LoginArgs), + /// App and module management. + App(app::AppArgs), +} + +impl Cli { + pub fn run(self) -> Result<()> { + match self.command { + Command::Login(args) => login::run(args), + Command::App(args) => app::run(args), + } + } +} diff --git a/src/credentials/mod.rs b/src/credentials/mod.rs new file mode 100644 index 0000000..beb1f56 --- /dev/null +++ b/src/credentials/mod.rs @@ -0,0 +1,101 @@ +//! Persisted OAuth tokens. File location is +//! `/mirrorstack/cli/credentials.json` — `~/.config` on +//! Linux, `~/Library/Application Support` on macOS, `%APPDATA%` on +//! Windows. The `cli` segment reserves room for future MirrorStack +//! tools (SDK, daemons, GUIs) under the same parent. Mode 0600 on Unix. + +use std::fs; +use std::io::{self, Write}; +use std::path::PathBuf; +use std::time::SystemTime; + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use tempfile::NamedTempFile; +use thiserror::Error; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Credentials { + pub access_token: String, + pub refresh_token: String, + #[serde(with = "humantime_serde_compat")] + pub expires_at: SystemTime, +} + +#[derive(Debug, Error)] +#[allow(dead_code)] // NotFound is matched in load(); load() is API for future commands +pub enum LoadError { + #[error("credentials: not found (run `mirrorstack login`)")] + NotFound, + #[error("credentials: I/O: {0}")] + Io(#[from] io::Error), + #[error("credentials: decode: {0}")] + Decode(#[from] serde_json::Error), + #[error("credentials: locate config dir")] + NoConfigDir, +} + +pub fn path() -> Result { + let dir = dirs::config_dir().ok_or(LoadError::NoConfigDir)?; + Ok(dir.join("mirrorstack").join("cli").join("credentials.json")) +} + +/// Atomically write `creds` to disk with mode 0600 on Unix. Atomic = +/// write to a temp file in the same directory, then rename — protects +/// against truncated files if the process is killed mid-write. +pub fn save(creds: &Credentials) -> Result<()> { + let p = path().context("credentials: path")?; + let parent = p.parent().expect("credentials path has parent"); + fs::create_dir_all(parent).context("credentials: mkdir")?; + + let mut tmp = NamedTempFile::new_in(parent).context("credentials: tempfile")?; + let json = serde_json::to_vec_pretty(creds).context("credentials: encode")?; + tmp.as_file_mut().write_all(&json).context("credentials: write")?; + tmp.as_file_mut().flush().context("credentials: flush")?; + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o600)) + .context("credentials: chmod")?; + } + + tmp.persist(&p) + .map_err(|e| anyhow::anyhow!("credentials: rename: {e}"))?; + Ok(()) +} + +#[allow(dead_code)] // API surface for future commands (whoami, etc.) +pub fn load() -> Result { + let p = path()?; + match fs::read(&p) { + Ok(bytes) => Ok(serde_json::from_slice(&bytes)?), + Err(e) if e.kind() == io::ErrorKind::NotFound => Err(LoadError::NotFound), + Err(e) => Err(LoadError::Io(e)), + } +} + +/// Encode `SystemTime` as RFC 3339 in JSON. Avoids pulling chrono just +/// for this; serde_json's default for SystemTime is a tagged struct +/// which is ugly on disk. +mod humantime_serde_compat { + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize(t: &SystemTime, s: S) -> Result { + let secs = t + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0); + s.serialize_f64(secs) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result { + let secs = f64::deserialize(d)?; + Ok(UNIX_EPOCH + Duration::from_secs_f64(secs)) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/credentials/tests.rs b/src/credentials/tests.rs new file mode 100644 index 0000000..aaf58e5 --- /dev/null +++ b/src/credentials/tests.rs @@ -0,0 +1,61 @@ +use super::*; + +use std::time::{Duration, SystemTime}; + +/// Redirect `dirs::config_dir()` for the duration of the test by setting +/// the per-platform env var the dirs crate consults. Returns the temp +/// dir guard — drop releases the dir. +fn with_temp_config_dir() -> tempfile::TempDir { + let dir = tempfile::tempdir().expect("tempdir"); + #[cfg(target_os = "macos")] + unsafe { + std::env::set_var("HOME", dir.path()) + }; + #[cfg(target_os = "windows")] + unsafe { + std::env::set_var("APPDATA", dir.path()) + }; + #[cfg(all(unix, not(target_os = "macos")))] + unsafe { + std::env::set_var("XDG_CONFIG_HOME", dir.path()) + }; + dir +} + +/// Cargo test runs cases in parallel by default, but every case here +/// mutates the same per-platform env var that `dirs::config_dir` reads. +/// Merging into a single test avoids the race without pulling in the +/// `serial_test` crate. +#[test] +fn credentials_lifecycle() { + let _g = with_temp_config_dir(); + + // load() before save() returns NotFound. + assert!(matches!(load(), Err(LoadError::NotFound))); + + // save → load roundtrip preserves token strings + expires_at. + let want = Credentials { + access_token: "AT".into(), + refresh_token: "RT".into(), + expires_at: SystemTime::now() + Duration::from_secs(900), + }; + save(&want).expect("save"); + let got = load().expect("load"); + assert_eq!(got.access_token, want.access_token); + assert_eq!(got.refresh_token, want.refresh_token); + let skew = got + .expires_at + .duration_since(want.expires_at) + .or_else(|_| want.expires_at.duration_since(got.expires_at)) + .unwrap(); + assert!(skew < Duration::from_millis(1), "skew = {skew:?}"); + + // File mode 0600 on Unix. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let p = path().expect("path"); + let mode = std::fs::metadata(&p).expect("stat").permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "got {mode:o}, want 0600"); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..10baf96 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,23 @@ +//! Entry point. Argument parsing and top-level command dispatch live in +//! `commands::Cli`. + +use std::process::ExitCode; + +use clap::Parser; + +mod auth; +mod browser; +mod commands; +mod credentials; +mod scaffold; + +fn main() -> ExitCode { + let cli = commands::Cli::parse(); + match cli.run() { + Ok(()) => ExitCode::SUCCESS, + Err(err) => { + eprintln!("error: {err:#}"); + ExitCode::FAILURE + } + } +} diff --git a/src/scaffold/mod.rs b/src/scaffold/mod.rs new file mode 100644 index 0000000..fc3e5d8 --- /dev/null +++ b/src/scaffold/mod.rs @@ -0,0 +1,69 @@ +//! `mirrorstack app module init ` — creates a fresh module +//! directory in CWD with a Go API skeleton, sql migrations stubs, and +//! a TS web frontend skeleton. + +use std::fs; +use std::path::Path; + +use anyhow::{Context, Result, anyhow}; + +mod templates; +mod validate; + +pub fn run_init(name: &str) -> Result<()> { + validate::name(name)?; + if Path::new(name).exists() { + return Err(anyhow!("directory {name:?} already exists")); + } + + println!("Creating module: {name}\n"); + let title = to_title(name); + + for (rel_path, content) in templates::files(name, &title) { + let full = Path::new(name).join(&rel_path); + if let Some(parent) = full.parent() { + fs::create_dir_all(parent).with_context(|| format!("create dir {}", parent.display()))?; + } + fs::write(&full, content).with_context(|| format!("write {}", full.display()))?; + println!(" created {rel_path}"); + } + + println!("\nDone! Next steps:"); + println!(" cd {name}"); + println!(" mirrorstack dev"); + Ok(()) +} + +/// "my-cool-module" → "MyCoolModule" +fn to_title(name: &str) -> String { + name.split('-') + .filter(|s| !s.is_empty()) + .map(|s| { + let mut c = s.chars(); + c.next() + .map(|f| f.to_uppercase().chain(c).collect::()) + .unwrap_or_default() + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn to_title_simple() { + assert_eq!(to_title("foo"), "Foo"); + } + + #[test] + fn to_title_hyphenated() { + assert_eq!(to_title("my-cool-module"), "MyCoolModule"); + } + + #[test] + fn to_title_handles_empty_segments() { + assert_eq!(to_title("foo--bar"), "FooBar"); + assert_eq!(to_title(""), ""); + } +} diff --git a/src/scaffold/templates.rs b/src/scaffold/templates.rs new file mode 100644 index 0000000..b0c995f --- /dev/null +++ b/src/scaffold/templates.rs @@ -0,0 +1,260 @@ +//! Static templates for the module scaffold. The Go version inlined +//! these as fmt.Sprintf calls; we keep the same shape (raw-string +//! literals + format! for substitutions) so the diff is reviewable +//! against scaffold/templates.go in the Go reference. + +/// Returns (relative_path, file_contents) pairs for every file the +/// scaffold creates. +pub fn files(name: &str, title: &str) -> Vec<(String, String)> { + vec![ + ("mirrorstack.yaml".into(), mirrorstack_yaml(name, title)), + ("MIRRORSTACK.md".into(), mirrorstack_md(title)), + (".gitignore".into(), gitignore().into()), + ("sql/0000_initial.up.sql".into(), initial_up_sql().into()), + ("sql/0000_initial.down.sql".into(), initial_down_sql().into()), + ("api/go.mod".into(), go_mod(name)), + ("api/module.go".into(), module_go(name)), + ("api/cmd/main.go".into(), cmd_main_go(name)), + ("api/handler/public.go".into(), handler_public_go(title)), + ("api/handler/admin.go".into(), handler_admin_go().into()), + (format!("api/service/{name}.go"), service_go(title)), + ("api/db/sqlc.yaml".into(), sqlc_yaml().into()), + (format!("api/db/queries/{name}.sql"), queries_sql(title)), + ("web/package.json".into(), web_package_json(name)), + ("web/platform/index.ts".into(), web_index(title)), + (format!("web/platform/pages/{title}Page.tsx"), web_platform_page(title)), + ("web/app/index.ts".into(), web_index(title)), + (format!("web/app/pages/{title}Page.tsx"), web_app_page(title)), + ] +} + +fn mirrorstack_yaml(name: &str, title: &str) -> String { + format!( + "id: {name}\n\ + name: {title}\n\ + description: \"\"\n\ + icon: extension\n\ + category: content\n\ + version: \"0.1.0\"\n\ + \n\ + dependencies: []\n\ + optional_dependencies: []\n\ + \n\ + platform:\n\ + nav_items:\n\ + - icon: extension\n\ + label: {title}\n\ + route: /{name}\n\ + \n\ + pages:\n\ + - route: /{name}\n\ + component: {title}Page\n\ + \n\ + app:\n\ + pages:\n\ + - route: /{name}\n\ + component: {title}Page\n", + ) +} + +fn mirrorstack_md(title: &str) -> String { + format!( + "# {title} Module\n\ + \n\ + TODO: Describe what this module does.\n\ + \n\ + ## Capabilities\n\ + - TODO\n\ + \n\ + ## When to use\n\ + - TODO\n\ + \n\ + ## Data model\n\ + - TODO\n\ + \n\ + ## Relationships\n\ + - Depends on: TODO\n", + ) +} + +fn gitignore() -> &'static str { + ".DS_Store\n\ + api/bootstrap\n\ + api/lambda.zip\n\ + web/dist/\n\ + web/node_modules/\n" +} + +fn initial_up_sql() -> &'static str { + "-- Create your tables here\n\ + -- This runs inside each app's schema (search_path is set automatically)\n\ + \n\ + -- CREATE TABLE items (\n\ + -- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n\ + -- title TEXT NOT NULL,\n\ + -- created_at TIMESTAMPTZ NOT NULL DEFAULT now()\n\ + -- );\n" +} + +fn initial_down_sql() -> &'static str { + "-- Reverse of 0000_initial.up.sql\n\ + \n\ + -- DROP TABLE IF EXISTS items;\n" +} + +fn go_mod(name: &str) -> String { + format!( + "module github.com/mirrorstack-ai/app-mod-{name}\n\ + \n\ + go 1.24\n\ + \n\ + // require github.com/mirrorstack-ai/app-module-sdk v0.1.0\n", + ) +} + +fn module_go(name: &str) -> String { + format!( + "package {name}\n\ + \n\ + import (\n\ + \t\"github.com/go-chi/chi/v5\"\n\ + \t// modulesdk \"github.com/mirrorstack-ai/app-module-sdk\"\n\ + )\n\ + \n\ + type Module struct {{\n\ + \t// pool *pgxpool.Pool\n\ + }}\n\ + \n\ + func New() *Module {{\n\ + \treturn &Module{{}}\n\ + }}\n\ + \n\ + func (m *Module) ID() string {{\n\ + \treturn \"{name}\"\n\ + }}\n\ + \n\ + func (m *Module) Routes(r chi.Router) {{\n\ + \t// TODO: mount handlers\n\ + }}\n", + ) +} + +fn cmd_main_go(name: &str) -> String { + format!( + "package main\n\ + \n\ + import (\n\ + \t\"fmt\"\n\ + \t\"net/http\"\n\ + \t\"os\"\n\ + \n\ + \t\"github.com/go-chi/chi/v5\"\n\ + \t// modulesdk \"github.com/mirrorstack-ai/app-module-sdk\"\n\ + \t// \"{name}\" module package\n\ + )\n\ + \n\ + func main() {{\n\ + \tr := chi.NewRouter()\n\ + \t// r.Use(modulesdk.ExtractContext)\n\ + \n\ + \tr.Get(\"/health\", func(w http.ResponseWriter, r *http.Request) {{\n\ + \t\tw.Write([]byte(\"ok\"))\n\ + \t}})\n\ + \n\ + \t// mod := {name}.New()\n\ + \t// mod.Routes(r)\n\ + \n\ + \tport := os.Getenv(\"PORT\")\n\ + \tif port == \"\" {{\n\ + \t\tport = \"8080\"\n\ + \t}}\n\ + \n\ + \tfmt.Printf(\"listening on :%s\\n\", port)\n\ + \thttp.ListenAndServe(\":\"+port, r)\n\ + }}\n", + ) +} + +fn handler_public_go(title: &str) -> String { + format!( + "package handler\n\ + \n\ + // Public handlers — end user routes (requires app user JWT)\n\ + \n\ + type Handler struct {{\n\ + \t// service *service.{title}Service\n\ + }}\n\ + \n\ + func New() *Handler {{\n\ + \treturn &Handler{{}}\n\ + }}\n", + ) +} + +fn handler_admin_go() -> &'static str { + "package handler\n\ + \n\ + // Admin handlers — app owner routes (requires app user JWT + admin role)\n" +} + +fn service_go(title: &str) -> String { + format!( + "package service\n\ + \n\ + type {title}Service struct {{\n\ + \t// pool *pgxpool.Pool\n\ + }}\n\ + \n\ + func New() *{title}Service {{\n\ + \treturn &{title}Service{{}}\n\ + }}\n", + ) +} + +fn sqlc_yaml() -> &'static str { + "version: \"2\"\n\ + sql:\n\ + - engine: \"postgresql\"\n\ + queries: \"queries/\"\n\ + schema: \"../../sql/*.up.sql\"\n\ + gen:\n\ + go:\n\ + package: \"generated\"\n\ + out: \"generated\"\n\ + sql_package: \"pgx/v5\"\n\ + emit_json_tags: true\n\ + overrides:\n\ + - db_type: \"uuid\"\n\ + go_type: \"github.com/jackc/pgx/v5/pgtype.UUID\"\n\ + - db_type: \"timestamptz\"\n\ + go_type: \"github.com/jackc/pgx/v5/pgtype.Timestamptz\"\n" +} + +fn queries_sql(title: &str) -> String { + format!( + "-- name: List{title} :many\n\ + -- SELECT * FROM items ORDER BY created_at DESC LIMIT $1 OFFSET $2;\n", + ) +} + +fn web_package_json(name: &str) -> String { + format!( + "{{\n \"name\": \"@mirrorstack-ai/mod-{name}-web\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"type\": \"module\"\n}}\n", + ) +} + +fn web_index(title: &str) -> String { + format!("export {{ {title}Page }} from \"./pages/{title}Page\";\n") +} + +fn web_platform_page(title: &str) -> String { + format!( + "export function {title}Page() {{\n return (\n
\n

{title}

\n

Platform dashboard page

\n
\n );\n}}\n", + ) +} + +fn web_app_page(title: &str) -> String { + format!( + "export function {title}Page() {{\n return (\n
\n

{title}

\n

App page

\n
\n );\n}}\n", + ) +} diff --git a/src/scaffold/validate.rs b/src/scaffold/validate.rs new file mode 100644 index 0000000..5835adc --- /dev/null +++ b/src/scaffold/validate.rs @@ -0,0 +1,51 @@ +use anyhow::{Result, anyhow}; + +/// `^[a-z][a-z0-9-]*$`, length 2..=40. Matches the Go reference impl +/// (scaffold/validate.go in the previous Go CLI). +pub fn name(s: &str) -> Result<()> { + let len = s.chars().count(); + if !(2..=40).contains(&len) { + return Err(anyhow!("module name must be 2-40 characters, got {len}")); + } + let mut chars = s.chars(); + let first = chars.next().unwrap(); + if !first.is_ascii_lowercase() { + return Err(anyhow!( + "module name must start with a lowercase letter (e.g., my-analytics)" + )); + } + for c in chars { + if !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') { + return Err(anyhow!( + "module name must be lowercase alphanumeric with hyphens (e.g., my-analytics)" + )); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_valid_names() { + for n in ["my-mod", "ab", "abcdef", "a1-b2-c3"] { + assert!(name(n).is_ok(), "expected {n:?} to be valid"); + } + } + + #[test] + fn rejects_invalid_names() { + for n in [ + "a", // too short + "Foo", // uppercase first + "1foo", // leading digit + "foo_bar", // underscore + "foo bar", // space + "-foo", // leading hyphen + ] { + assert!(name(n).is_err(), "expected {n:?} to be invalid"); + } + } +} From 9ffae52c88486e7f49f24c53d577871d98158700 Mon Sep 17 00:00:00 2001 From: Sheng Kun Chang Date: Thu, 30 Apr 2026 14:00:50 +0800 Subject: [PATCH 2/6] feat(cli): load .env from CWD on startup Local-dev convenience: copy .env.example to .env and the CLI picks up MIRRORSTACK_API_URL / MIRRORSTACK_WEB_URL without prefixing every invocation. Process env still wins when both are set, so per-call overrides keep working. - dotenvy::dotenv().ok() at the top of main, before clap parses args - .env.example checked in with the localhost defaults - .env added to .gitignore (real values stay local) Co-Authored-By: Claude Opus 4.7 (1M context) --- .env.example | 5 +++++ .gitignore | 1 + Cargo.lock | 7 +++++++ Cargo.toml | 1 + README.md | 10 +++++++++- src/main.rs | 5 +++++ 6 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..727b709 --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +# Copy this file to `.env` for local development. +# Process env vars override .env if both are set. + +MIRRORSTACK_API_URL=http://localhost:8081 +MIRRORSTACK_WEB_URL=http://localhost:3000 diff --git a/.gitignore b/.gitignore index b52a2cc..a7763c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .DS_Store /target dist/ +.env diff --git a/Cargo.lock b/Cargo.lock index 07fa36b..862f7d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -254,6 +254,12 @@ dependencies = [ "syn", ] +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + [[package]] name = "equivalent" version = "1.0.2" @@ -806,6 +812,7 @@ dependencies = [ "base64", "clap", "dirs", + "dotenvy", "mockito", "open", "rand", diff --git a/Cargo.toml b/Cargo.toml index e04ffcb..1903db7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ open = "5" anyhow = "1" thiserror = "2" tempfile = "3" +dotenvy = "0.15" [dev-dependencies] mockito = "1.6" diff --git a/README.md b/README.md index c68a62f..590709a 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,15 @@ cargo build cargo test ``` -Run against local services: +Run against local services. Easiest is a `.env` file in the project +root — copy `.env.example` and edit: + +```bash +cp .env.example .env +cargo run -- login +``` + +Or set the env vars per-invocation (these always win over `.env`): ```bash MIRRORSTACK_API_URL=http://localhost:8081 \ diff --git a/src/main.rs b/src/main.rs index 10baf96..c10d0dd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,11 @@ mod credentials; mod scaffold; fn main() -> ExitCode { + // Load .env from CWD if present. Process env vars still take precedence + // over .env, so users can override per-invocation. Silently ignored + // when no .env exists (the common case for installed users). + let _ = dotenvy::dotenv(); + let cli = commands::Cli::parse(); match cli.run() { Ok(()) => ExitCode::SUCCESS, From e4ddc2df65514804c81240bcdcf5ff5d0541b788 Mon Sep 17 00:00:00 2001 From: Sheng Kun Chang Date: Thu, 30 Apr 2026 14:03:51 +0800 Subject: [PATCH 3/6] feat(whoami): mirrorstack whoami command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prints the authenticated user identity. Reads access_token from the saved credentials file, calls GET /v1/auth/me with Authorization: Bearer, and renders email + name + slug + id. Friendly errors: - "not signed in. Run mirrorstack login..." when no credentials file - "session expired. Run mirrorstack login..." on 401/403 New module src/api.rs hosts authenticated API calls; whoami is the first caller. Future commands (logout, apps list, etc.) will reuse the same module. Auto-refresh on token expiry is a follow-up — for v1 the user re-runs login. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/api.rs | 108 +++++++++++++++++++++++++++++++++++++++++ src/commands/mod.rs | 4 ++ src/commands/whoami.rs | 50 +++++++++++++++++++ src/main.rs | 1 + 4 files changed, 163 insertions(+) create mode 100644 src/api.rs create mode 100644 src/commands/whoami.rs diff --git a/src/api.rs b/src/api.rs new file mode 100644 index 0000000..8974022 --- /dev/null +++ b/src/api.rs @@ -0,0 +1,108 @@ +//! Authenticated calls to the api-platform account service. Endpoints +//! that require a session expect `Authorization: Bearer `. + +use std::time::Duration; + +use reqwest::blocking::Client; +use serde::Deserialize; +use thiserror::Error; + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] // profile_url is part of the API surface; whoami doesn't print it yet +pub struct Identity { + pub id: String, + pub email: String, + pub name: String, + #[serde(default)] + pub profile_url: Option, + #[serde(default)] + pub slug: Option, +} + +#[derive(Debug, Error)] +pub enum ApiError { + #[error("not signed in or session expired — run `mirrorstack login` again")] + Unauthenticated, + #[error("api: HTTP error: {0}")] + Http(#[from] reqwest::Error), + #[error("api: decode response: {0}")] + Decode(#[from] serde_json::Error), + #[error("api: unexpected response {status}: {body}")] + Unexpected { status: u16, body: String }, + #[error("api: build HTTP client")] + BuildClient, +} + +/// GET /v1/auth/me — returns the authenticated user's identity. +pub fn me(api_base: &str, access_token: &str) -> Result { + let endpoint = format!("{}/v1/auth/me", api_base.trim_end_matches('/')); + let http = Client::builder() + .timeout(Duration::from_secs(15)) + .build() + .map_err(|_| ApiError::BuildClient)?; + + let resp = http + .get(&endpoint) + .bearer_auth(access_token) + .header("Accept", "application/json") + .send()?; + + let status = resp.status(); + let body = resp.text()?; + + if status.is_success() { + return Ok(serde_json::from_str(&body)?); + } + if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN { + return Err(ApiError::Unauthenticated); + } + Err(ApiError::Unexpected { + status: status.as_u16(), + body, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + use mockito::Server; + use serde_json::json; + + #[test] + fn me_success() { + let mut server = Server::new(); + let _m = server + .mock("GET", "/v1/auth/me") + .match_header("authorization", "Bearer AT") + .with_status(200) + .with_body( + json!({ + "id": "u-1", + "email": "user@example.com", + "name": "Test User", + "profile_url": null, + "slug": "test-user" + }) + .to_string(), + ) + .create(); + + let id = me(&server.url(), "AT").expect("ok"); + assert_eq!(id.email, "user@example.com"); + assert_eq!(id.slug.as_deref(), Some("test-user")); + } + + #[test] + fn me_401_is_unauthenticated() { + let mut server = Server::new(); + let _m = server + .mock("GET", "/v1/auth/me") + .with_status(401) + .with_body(r#"{"error":{"code":"token_invalid"}}"#) + .create(); + + let err = me(&server.url(), "expired").unwrap_err(); + assert!(matches!(err, ApiError::Unauthenticated), "got {err:?}"); + } +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index bd6c572..09fbad0 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -6,6 +6,7 @@ use clap::{Parser, Subcommand}; mod app; mod login; +mod whoami; /// Official command-line tool for the MirrorStack platform. #[derive(Parser)] @@ -19,6 +20,8 @@ pub struct Cli { enum Command { /// Sign in to MirrorStack via OAuth. Login(login::LoginArgs), + /// Print the currently signed-in user. + Whoami(whoami::WhoamiArgs), /// App and module management. App(app::AppArgs), } @@ -27,6 +30,7 @@ impl Cli { pub fn run(self) -> Result<()> { match self.command { Command::Login(args) => login::run(args), + Command::Whoami(args) => whoami::run(args), Command::App(args) => app::run(args), } } diff --git a/src/commands/whoami.rs b/src/commands/whoami.rs new file mode 100644 index 0000000..466b72a --- /dev/null +++ b/src/commands/whoami.rs @@ -0,0 +1,50 @@ +//! `mirrorstack whoami` — print the authenticated user. +//! +//! Reads the access token from the credentials file and calls +//! GET /v1/auth/me. If the file is missing or the server returns 401, +//! tells the user to run `mirrorstack login`. Auto-refresh on token +//! expiry is a follow-up — for v1 the user re-runs login. + +use anyhow::{Result, anyhow}; +use clap::Args; + +use crate::api::{self, ApiError}; +use crate::credentials::{self, LoadError}; + +const DEFAULT_API_BASE: &str = "https://api.mirrorstack.ai"; +const ENV_API_URL: &str = "MIRRORSTACK_API_URL"; + +#[derive(Args)] +pub struct WhoamiArgs {} + +pub fn run(_args: WhoamiArgs) -> Result<()> { + let creds = match credentials::load() { + Ok(c) => c, + Err(LoadError::NotFound) => { + return Err(anyhow!( + "not signed in. Run `mirrorstack login` to sign in." + )); + } + Err(e) => return Err(e.into()), + }; + + let api_base = std::env::var(ENV_API_URL).unwrap_or_else(|_| DEFAULT_API_BASE.into()); + + match api::me(&api_base, &creds.access_token) { + Ok(id) => { + println!("{}", id.email); + if !id.name.is_empty() { + println!(" name: {}", id.name); + } + if let Some(slug) = id.slug.as_deref() { + println!(" slug: @{slug}"); + } + println!(" id: {}", id.id); + Ok(()) + } + Err(ApiError::Unauthenticated) => Err(anyhow!( + "session expired. Run `mirrorstack login` to sign in again." + )), + Err(e) => Err(e.into()), + } +} diff --git a/src/main.rs b/src/main.rs index c10d0dd..705252a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ use std::process::ExitCode; use clap::Parser; +mod api; mod auth; mod browser; mod commands; From 0d403446a946087be0c284e15639eb3a5f5a3623 Mon Sep 17 00:00:00 2001 From: Sheng Kun Chang Date: Thu, 30 Apr 2026 14:09:52 +0800 Subject: [PATCH 4/6] =?UTF-8?q?refactor:=20/simplify=20pass=20=E2=80=94=20?= =?UTF-8?q?body=20limits,=20dedupe=20constants,=20tighter=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Findings from the multi-agent review applied: - /token and /me responses now read through Read::take(64KB) so a hostile endpoint can't OOM the CLI with a giant body. Success path uses reqwest's resp.json::() helper; the error path bounds the read explicitly. - DEFAULT_API_BASE, DEFAULT_WEB_BASE, ENV_API_URL, ENV_WEB_URL hoisted to commands/mod.rs. login + whoami now share one definition. - ApiError::BuildClient (which discarded the source error) replaced by the existing #[from] reqwest::Error path. Reqwest builder failures (e.g. TLS config) keep their cause. - scaffold::run_init no longer Path::exists()-pre-checks before fs::create_dir; just calls create_dir and matches AlreadyExists. Sidesteps the TOCTOU race between check and write. Skipped with reason: - Shared error base for auth+api: only 2 modules; premature - Removing url dep: tests and AuthorizeURL builder use it directly, reqwest's re-export version pinning is fragile - Lazy iterator over scaffold templates: 18 entries; not worth it - AuthError::Other vs Unexpected collapse: mild overlap, not worth churn - authorize_url unwrap_or_else fallback: defensive, will revisit if it ever masks a bug Co-Authored-By: Claude Opus 4.7 (1M context) --- src/api.rs | 20 ++++++++++++++------ src/auth/mod.rs | 27 ++++++++++++++++++++++++--- src/commands/login.rs | 5 +---- src/commands/mod.rs | 10 ++++++++++ src/commands/whoami.rs | 3 +-- src/scaffold/mod.rs | 13 +++++++++++-- 6 files changed, 61 insertions(+), 17 deletions(-) diff --git a/src/api.rs b/src/api.rs index 8974022..06390b6 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,12 +1,15 @@ //! Authenticated calls to the api-platform account service. Endpoints //! that require a session expect `Authorization: Bearer `. +use std::io::Read; use std::time::Duration; use reqwest::blocking::Client; use serde::Deserialize; use thiserror::Error; +const MAX_RESPONSE_BYTES: u64 = 64 * 1024; + #[derive(Debug, Deserialize)] #[allow(dead_code)] // profile_url is part of the API surface; whoami doesn't print it yet pub struct Identity { @@ -29,8 +32,6 @@ pub enum ApiError { Decode(#[from] serde_json::Error), #[error("api: unexpected response {status}: {body}")] Unexpected { status: u16, body: String }, - #[error("api: build HTTP client")] - BuildClient, } /// GET /v1/auth/me — returns the authenticated user's identity. @@ -38,8 +39,7 @@ pub fn me(api_base: &str, access_token: &str) -> Result { let endpoint = format!("{}/v1/auth/me", api_base.trim_end_matches('/')); let http = Client::builder() .timeout(Duration::from_secs(15)) - .build() - .map_err(|_| ApiError::BuildClient)?; + .build()?; let resp = http .get(&endpoint) @@ -48,14 +48,22 @@ pub fn me(api_base: &str, access_token: &str) -> Result { .send()?; let status = resp.status(); - let body = resp.text()?; if status.is_success() { - return Ok(serde_json::from_str(&body)?); + return Ok(resp.json::()?); } if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN { return Err(ApiError::Unauthenticated); } + // Bound the error-path body so a hostile endpoint can't OOM us. + let mut body = Vec::with_capacity(1024); + resp.take(MAX_RESPONSE_BYTES) + .read_to_end(&mut body) + .map_err(|e| ApiError::Unexpected { + status: status.as_u16(), + body: format!("(read body failed: {e})"), + })?; + let body = String::from_utf8_lossy(&body).into_owned(); Err(ApiError::Unexpected { status: status.as_u16(), body, diff --git a/src/auth/mod.rs b/src/auth/mod.rs index ba29369..d013725 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -5,16 +5,23 @@ //! displayed on the consent page back into the terminal. Custom-scheme //! and per-OS handler registration is the follow-up tracked at #7. +use std::io::Read; + use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use rand::TryRngCore; use rand::rngs::OsRng; -use reqwest::blocking::Client; +use reqwest::blocking::{Client, Response}; use serde::Deserialize; use sha2::{Digest, Sha256}; use thiserror::Error; use url::Url; +/// Cap on response bodies we'll deserialize. /token and /me return +/// sub-1KB JSON in practice; 64 KiB is generous slack and protects +/// against a hostile endpoint trying to OOM the CLI. +const MAX_RESPONSE_BYTES: u64 = 64 * 1024; + /// Identifies the CLI to the platform; matches the seed in /// api-platform migration `011_oauth.up.sql`. pub const CLIENT_ID: &str = "mirrorstack-cli"; @@ -99,13 +106,16 @@ pub fn exchange_code( .map_err(AuthError::Http)?; let status = resp.status(); - let body = resp.text().map_err(AuthError::Http)?; if status.is_success() { - return serde_json::from_str(&body).map_err(|e| AuthError::Decode(e.to_string())); + return resp + .json::() + .map_err(|e| AuthError::Decode(e.to_string())); } // RFC 6749 §5.2 error body — map known codes to typed sentinels. + // Cap body so a hostile endpoint can't OOM us with a giant response. + let body = read_capped(resp)?; let parsed: ErrorBody = serde_json::from_str(&body).unwrap_or_default(); match parsed.error.as_deref() { Some("invalid_grant") => Err(AuthError::InvalidGrant), @@ -163,5 +173,16 @@ fn random_b64url(n: usize) -> Result { Ok(URL_SAFE_NO_PAD.encode(buf)) } +/// Read a response body into memory with a hard size cap. Truncated +/// bodies are returned as-is — the JSON parse downstream will fail +/// loudly rather than silently misinterpret a partial document. +fn read_capped(resp: Response) -> Result { + let mut buf = Vec::with_capacity(1024); + resp.take(MAX_RESPONSE_BYTES) + .read_to_end(&mut buf) + .map_err(|e| AuthError::Decode(e.to_string()))?; + String::from_utf8(buf).map_err(|e| AuthError::Decode(e.to_string())) +} + #[cfg(test)] mod tests; diff --git a/src/commands/login.rs b/src/commands/login.rs index ea68e8c..eb814b3 100644 --- a/src/commands/login.rs +++ b/src/commands/login.rs @@ -17,10 +17,7 @@ use crate::auth::{self, AuthError}; use crate::browser; use crate::credentials::{self, Credentials}; -const DEFAULT_API_BASE: &str = "https://api.mirrorstack.ai"; -const DEFAULT_WEB_BASE: &str = "https://account.mirrorstack.ai"; -const ENV_API_URL: &str = "MIRRORSTACK_API_URL"; -const ENV_WEB_URL: &str = "MIRRORSTACK_WEB_URL"; +use super::{DEFAULT_API_BASE, DEFAULT_WEB_BASE, ENV_API_URL, ENV_WEB_URL}; #[derive(Args)] pub struct LoginArgs {} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 09fbad0..d43362e 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -8,6 +8,16 @@ mod app; mod login; mod whoami; +/// Default api-platform host. Override per-invocation with +/// `MIRRORSTACK_API_URL` (or via `.env`). +pub(crate) const DEFAULT_API_BASE: &str = "https://api.mirrorstack.ai"; + +/// Default web-account host. Override with `MIRRORSTACK_WEB_URL`. +pub(crate) const DEFAULT_WEB_BASE: &str = "https://account.mirrorstack.ai"; + +pub(crate) const ENV_API_URL: &str = "MIRRORSTACK_API_URL"; +pub(crate) const ENV_WEB_URL: &str = "MIRRORSTACK_WEB_URL"; + /// Official command-line tool for the MirrorStack platform. #[derive(Parser)] #[command(name = "mirrorstack", version, about, long_about = None)] diff --git a/src/commands/whoami.rs b/src/commands/whoami.rs index 466b72a..b5dd5cd 100644 --- a/src/commands/whoami.rs +++ b/src/commands/whoami.rs @@ -11,8 +11,7 @@ use clap::Args; use crate::api::{self, ApiError}; use crate::credentials::{self, LoadError}; -const DEFAULT_API_BASE: &str = "https://api.mirrorstack.ai"; -const ENV_API_URL: &str = "MIRRORSTACK_API_URL"; +use super::{DEFAULT_API_BASE, ENV_API_URL}; #[derive(Args)] pub struct WhoamiArgs {} diff --git a/src/scaffold/mod.rs b/src/scaffold/mod.rs index fc3e5d8..ea80f8b 100644 --- a/src/scaffold/mod.rs +++ b/src/scaffold/mod.rs @@ -3,6 +3,7 @@ //! a TS web frontend skeleton. use std::fs; +use std::io; use std::path::Path; use anyhow::{Context, Result, anyhow}; @@ -12,8 +13,16 @@ mod validate; pub fn run_init(name: &str) -> Result<()> { validate::name(name)?; - if Path::new(name).exists() { - return Err(anyhow!("directory {name:?} already exists")); + + // Try to create the root directory first; if it already exists, + // refuse rather than scribbling files over a non-empty tree. This + // sidesteps the TOCTOU pre-check `Path::exists()` would have made. + match fs::create_dir(name) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + return Err(anyhow!("directory {name:?} already exists")); + } + Err(e) => return Err(e).with_context(|| format!("create dir {name}")), } println!("Creating module: {name}\n"); From 94566793aae2b59497705f8e07e1416b2c821395 Mon Sep 17 00:00:00 2001 From: Sheng Kun Chang Date: Thu, 30 Apr 2026 14:14:58 +0800 Subject: [PATCH 5/6] refactor: drop app/scaffold; ship login + whoami only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trim PR #8 to its essential scope. The scaffold command is tracked in #9 and lands in a follow-up PR — the validation regex and the 18 file templates are the chunky parts and aren't load-bearing for the auth pipeline this PR is about. Removes: - src/commands/app.rs (the App subcommand wrapper) - src/scaffold/{mod,templates,validate}.rs (~380 lines) - App variant + dispatch arm in src/commands/mod.rs - mod scaffold; in src/main.rs - "app module init" reference in README The dropped code can be lifted from the prior commits in this branch when #9 lands. Co-Authored-By: Claude Opus 4.7 (1M context) --- README.md | 20 +-- src/commands/app.rs | 41 ------ src/commands/mod.rs | 4 - src/main.rs | 1 - src/scaffold/mod.rs | 78 ------------ src/scaffold/templates.rs | 260 -------------------------------------- src/scaffold/validate.rs | 51 -------- 7 files changed, 7 insertions(+), 448 deletions(-) delete mode 100644 src/commands/app.rs delete mode 100644 src/scaffold/mod.rs delete mode 100644 src/scaffold/templates.rs delete mode 100644 src/scaffold/validate.rs diff --git a/README.md b/README.md index 590709a..3fac61a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MirrorStack CLI -Scaffold, develop, and deploy MirrorStack modules. +Official command-line tool for the MirrorStack platform. ## Install @@ -13,20 +13,14 @@ Pre-built releases (brew, scoop, deb) coming with the next milestone. ## Commands ```bash -mirrorstack login # Sign in via OAuth (PKCE) -mirrorstack app module init # Scaffold a new module -mirrorstack --help # Show help -mirrorstack --version # Show CLI version +mirrorstack login # Sign in via OAuth (PKCE) +mirrorstack whoami # Print the currently signed-in user +mirrorstack --help # Show help +mirrorstack --version # Show CLI version ``` -## Quick start - -```bash -mirrorstack login -mirrorstack app module init my-module -cd my-module -# Edit api/, web/, sql/ as needed -``` +Module scaffolding (`app module init`) is tracked separately and lands +in a follow-up PR. ## Local development diff --git a/src/commands/app.rs b/src/commands/app.rs deleted file mode 100644 index 05a007c..0000000 --- a/src/commands/app.rs +++ /dev/null @@ -1,41 +0,0 @@ -//! `mirrorstack app ...` — app and module management commands. - -use anyhow::Result; -use clap::{Args, Subcommand}; - -use crate::scaffold; - -#[derive(Args)] -pub struct AppArgs { - #[command(subcommand)] - command: AppCommand, -} - -#[derive(Subcommand)] -enum AppCommand { - /// Module management. - Module(ModuleArgs), -} - -#[derive(Args)] -struct ModuleArgs { - #[command(subcommand)] - command: ModuleCommand, -} - -#[derive(Subcommand)] -enum ModuleCommand { - /// Scaffold a new module in the current directory. - Init { - /// Module name (lowercase alphanumeric + hyphens, 2-40 chars). - name: String, - }, -} - -pub fn run(args: AppArgs) -> Result<()> { - match args.command { - AppCommand::Module(m) => match m.command { - ModuleCommand::Init { name } => scaffold::run_init(&name), - }, - } -} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index d43362e..9b79f69 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -4,7 +4,6 @@ use anyhow::Result; use clap::{Parser, Subcommand}; -mod app; mod login; mod whoami; @@ -32,8 +31,6 @@ enum Command { Login(login::LoginArgs), /// Print the currently signed-in user. Whoami(whoami::WhoamiArgs), - /// App and module management. - App(app::AppArgs), } impl Cli { @@ -41,7 +38,6 @@ impl Cli { match self.command { Command::Login(args) => login::run(args), Command::Whoami(args) => whoami::run(args), - Command::App(args) => app::run(args), } } } diff --git a/src/main.rs b/src/main.rs index 705252a..2ab2b2f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,6 @@ mod auth; mod browser; mod commands; mod credentials; -mod scaffold; fn main() -> ExitCode { // Load .env from CWD if present. Process env vars still take precedence diff --git a/src/scaffold/mod.rs b/src/scaffold/mod.rs deleted file mode 100644 index ea80f8b..0000000 --- a/src/scaffold/mod.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! `mirrorstack app module init ` — creates a fresh module -//! directory in CWD with a Go API skeleton, sql migrations stubs, and -//! a TS web frontend skeleton. - -use std::fs; -use std::io; -use std::path::Path; - -use anyhow::{Context, Result, anyhow}; - -mod templates; -mod validate; - -pub fn run_init(name: &str) -> Result<()> { - validate::name(name)?; - - // Try to create the root directory first; if it already exists, - // refuse rather than scribbling files over a non-empty tree. This - // sidesteps the TOCTOU pre-check `Path::exists()` would have made. - match fs::create_dir(name) { - Ok(()) => {} - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { - return Err(anyhow!("directory {name:?} already exists")); - } - Err(e) => return Err(e).with_context(|| format!("create dir {name}")), - } - - println!("Creating module: {name}\n"); - let title = to_title(name); - - for (rel_path, content) in templates::files(name, &title) { - let full = Path::new(name).join(&rel_path); - if let Some(parent) = full.parent() { - fs::create_dir_all(parent).with_context(|| format!("create dir {}", parent.display()))?; - } - fs::write(&full, content).with_context(|| format!("write {}", full.display()))?; - println!(" created {rel_path}"); - } - - println!("\nDone! Next steps:"); - println!(" cd {name}"); - println!(" mirrorstack dev"); - Ok(()) -} - -/// "my-cool-module" → "MyCoolModule" -fn to_title(name: &str) -> String { - name.split('-') - .filter(|s| !s.is_empty()) - .map(|s| { - let mut c = s.chars(); - c.next() - .map(|f| f.to_uppercase().chain(c).collect::()) - .unwrap_or_default() - }) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn to_title_simple() { - assert_eq!(to_title("foo"), "Foo"); - } - - #[test] - fn to_title_hyphenated() { - assert_eq!(to_title("my-cool-module"), "MyCoolModule"); - } - - #[test] - fn to_title_handles_empty_segments() { - assert_eq!(to_title("foo--bar"), "FooBar"); - assert_eq!(to_title(""), ""); - } -} diff --git a/src/scaffold/templates.rs b/src/scaffold/templates.rs deleted file mode 100644 index b0c995f..0000000 --- a/src/scaffold/templates.rs +++ /dev/null @@ -1,260 +0,0 @@ -//! Static templates for the module scaffold. The Go version inlined -//! these as fmt.Sprintf calls; we keep the same shape (raw-string -//! literals + format! for substitutions) so the diff is reviewable -//! against scaffold/templates.go in the Go reference. - -/// Returns (relative_path, file_contents) pairs for every file the -/// scaffold creates. -pub fn files(name: &str, title: &str) -> Vec<(String, String)> { - vec![ - ("mirrorstack.yaml".into(), mirrorstack_yaml(name, title)), - ("MIRRORSTACK.md".into(), mirrorstack_md(title)), - (".gitignore".into(), gitignore().into()), - ("sql/0000_initial.up.sql".into(), initial_up_sql().into()), - ("sql/0000_initial.down.sql".into(), initial_down_sql().into()), - ("api/go.mod".into(), go_mod(name)), - ("api/module.go".into(), module_go(name)), - ("api/cmd/main.go".into(), cmd_main_go(name)), - ("api/handler/public.go".into(), handler_public_go(title)), - ("api/handler/admin.go".into(), handler_admin_go().into()), - (format!("api/service/{name}.go"), service_go(title)), - ("api/db/sqlc.yaml".into(), sqlc_yaml().into()), - (format!("api/db/queries/{name}.sql"), queries_sql(title)), - ("web/package.json".into(), web_package_json(name)), - ("web/platform/index.ts".into(), web_index(title)), - (format!("web/platform/pages/{title}Page.tsx"), web_platform_page(title)), - ("web/app/index.ts".into(), web_index(title)), - (format!("web/app/pages/{title}Page.tsx"), web_app_page(title)), - ] -} - -fn mirrorstack_yaml(name: &str, title: &str) -> String { - format!( - "id: {name}\n\ - name: {title}\n\ - description: \"\"\n\ - icon: extension\n\ - category: content\n\ - version: \"0.1.0\"\n\ - \n\ - dependencies: []\n\ - optional_dependencies: []\n\ - \n\ - platform:\n\ - nav_items:\n\ - - icon: extension\n\ - label: {title}\n\ - route: /{name}\n\ - \n\ - pages:\n\ - - route: /{name}\n\ - component: {title}Page\n\ - \n\ - app:\n\ - pages:\n\ - - route: /{name}\n\ - component: {title}Page\n", - ) -} - -fn mirrorstack_md(title: &str) -> String { - format!( - "# {title} Module\n\ - \n\ - TODO: Describe what this module does.\n\ - \n\ - ## Capabilities\n\ - - TODO\n\ - \n\ - ## When to use\n\ - - TODO\n\ - \n\ - ## Data model\n\ - - TODO\n\ - \n\ - ## Relationships\n\ - - Depends on: TODO\n", - ) -} - -fn gitignore() -> &'static str { - ".DS_Store\n\ - api/bootstrap\n\ - api/lambda.zip\n\ - web/dist/\n\ - web/node_modules/\n" -} - -fn initial_up_sql() -> &'static str { - "-- Create your tables here\n\ - -- This runs inside each app's schema (search_path is set automatically)\n\ - \n\ - -- CREATE TABLE items (\n\ - -- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n\ - -- title TEXT NOT NULL,\n\ - -- created_at TIMESTAMPTZ NOT NULL DEFAULT now()\n\ - -- );\n" -} - -fn initial_down_sql() -> &'static str { - "-- Reverse of 0000_initial.up.sql\n\ - \n\ - -- DROP TABLE IF EXISTS items;\n" -} - -fn go_mod(name: &str) -> String { - format!( - "module github.com/mirrorstack-ai/app-mod-{name}\n\ - \n\ - go 1.24\n\ - \n\ - // require github.com/mirrorstack-ai/app-module-sdk v0.1.0\n", - ) -} - -fn module_go(name: &str) -> String { - format!( - "package {name}\n\ - \n\ - import (\n\ - \t\"github.com/go-chi/chi/v5\"\n\ - \t// modulesdk \"github.com/mirrorstack-ai/app-module-sdk\"\n\ - )\n\ - \n\ - type Module struct {{\n\ - \t// pool *pgxpool.Pool\n\ - }}\n\ - \n\ - func New() *Module {{\n\ - \treturn &Module{{}}\n\ - }}\n\ - \n\ - func (m *Module) ID() string {{\n\ - \treturn \"{name}\"\n\ - }}\n\ - \n\ - func (m *Module) Routes(r chi.Router) {{\n\ - \t// TODO: mount handlers\n\ - }}\n", - ) -} - -fn cmd_main_go(name: &str) -> String { - format!( - "package main\n\ - \n\ - import (\n\ - \t\"fmt\"\n\ - \t\"net/http\"\n\ - \t\"os\"\n\ - \n\ - \t\"github.com/go-chi/chi/v5\"\n\ - \t// modulesdk \"github.com/mirrorstack-ai/app-module-sdk\"\n\ - \t// \"{name}\" module package\n\ - )\n\ - \n\ - func main() {{\n\ - \tr := chi.NewRouter()\n\ - \t// r.Use(modulesdk.ExtractContext)\n\ - \n\ - \tr.Get(\"/health\", func(w http.ResponseWriter, r *http.Request) {{\n\ - \t\tw.Write([]byte(\"ok\"))\n\ - \t}})\n\ - \n\ - \t// mod := {name}.New()\n\ - \t// mod.Routes(r)\n\ - \n\ - \tport := os.Getenv(\"PORT\")\n\ - \tif port == \"\" {{\n\ - \t\tport = \"8080\"\n\ - \t}}\n\ - \n\ - \tfmt.Printf(\"listening on :%s\\n\", port)\n\ - \thttp.ListenAndServe(\":\"+port, r)\n\ - }}\n", - ) -} - -fn handler_public_go(title: &str) -> String { - format!( - "package handler\n\ - \n\ - // Public handlers — end user routes (requires app user JWT)\n\ - \n\ - type Handler struct {{\n\ - \t// service *service.{title}Service\n\ - }}\n\ - \n\ - func New() *Handler {{\n\ - \treturn &Handler{{}}\n\ - }}\n", - ) -} - -fn handler_admin_go() -> &'static str { - "package handler\n\ - \n\ - // Admin handlers — app owner routes (requires app user JWT + admin role)\n" -} - -fn service_go(title: &str) -> String { - format!( - "package service\n\ - \n\ - type {title}Service struct {{\n\ - \t// pool *pgxpool.Pool\n\ - }}\n\ - \n\ - func New() *{title}Service {{\n\ - \treturn &{title}Service{{}}\n\ - }}\n", - ) -} - -fn sqlc_yaml() -> &'static str { - "version: \"2\"\n\ - sql:\n\ - - engine: \"postgresql\"\n\ - queries: \"queries/\"\n\ - schema: \"../../sql/*.up.sql\"\n\ - gen:\n\ - go:\n\ - package: \"generated\"\n\ - out: \"generated\"\n\ - sql_package: \"pgx/v5\"\n\ - emit_json_tags: true\n\ - overrides:\n\ - - db_type: \"uuid\"\n\ - go_type: \"github.com/jackc/pgx/v5/pgtype.UUID\"\n\ - - db_type: \"timestamptz\"\n\ - go_type: \"github.com/jackc/pgx/v5/pgtype.Timestamptz\"\n" -} - -fn queries_sql(title: &str) -> String { - format!( - "-- name: List{title} :many\n\ - -- SELECT * FROM items ORDER BY created_at DESC LIMIT $1 OFFSET $2;\n", - ) -} - -fn web_package_json(name: &str) -> String { - format!( - "{{\n \"name\": \"@mirrorstack-ai/mod-{name}-web\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"type\": \"module\"\n}}\n", - ) -} - -fn web_index(title: &str) -> String { - format!("export {{ {title}Page }} from \"./pages/{title}Page\";\n") -} - -fn web_platform_page(title: &str) -> String { - format!( - "export function {title}Page() {{\n return (\n
\n

{title}

\n

Platform dashboard page

\n
\n );\n}}\n", - ) -} - -fn web_app_page(title: &str) -> String { - format!( - "export function {title}Page() {{\n return (\n
\n

{title}

\n

App page

\n
\n );\n}}\n", - ) -} diff --git a/src/scaffold/validate.rs b/src/scaffold/validate.rs deleted file mode 100644 index 5835adc..0000000 --- a/src/scaffold/validate.rs +++ /dev/null @@ -1,51 +0,0 @@ -use anyhow::{Result, anyhow}; - -/// `^[a-z][a-z0-9-]*$`, length 2..=40. Matches the Go reference impl -/// (scaffold/validate.go in the previous Go CLI). -pub fn name(s: &str) -> Result<()> { - let len = s.chars().count(); - if !(2..=40).contains(&len) { - return Err(anyhow!("module name must be 2-40 characters, got {len}")); - } - let mut chars = s.chars(); - let first = chars.next().unwrap(); - if !first.is_ascii_lowercase() { - return Err(anyhow!( - "module name must start with a lowercase letter (e.g., my-analytics)" - )); - } - for c in chars { - if !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') { - return Err(anyhow!( - "module name must be lowercase alphanumeric with hyphens (e.g., my-analytics)" - )); - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn accepts_valid_names() { - for n in ["my-mod", "ab", "abcdef", "a1-b2-c3"] { - assert!(name(n).is_ok(), "expected {n:?} to be valid"); - } - } - - #[test] - fn rejects_invalid_names() { - for n in [ - "a", // too short - "Foo", // uppercase first - "1foo", // leading digit - "foo_bar", // underscore - "foo bar", // space - "-foo", // leading hyphen - ] { - assert!(name(n).is_err(), "expected {n:?} to be invalid"); - } - } -} From f14e2ea73d8f05b8d2d3f7b9f3a66dcc8e1028f1 Mon Sep 17 00:00:00 2001 From: Sheng Kun Chang Date: Thu, 30 Apr 2026 14:19:59 +0800 Subject: [PATCH 6/6] ci: GitHub Actions workflow (fmt + clippy + cross-platform build) Three jobs on every push to main and every PR: - lint: cargo fmt --check + cargo clippy --all-targets with -D warnings (RUSTFLAGS) so any warning fails CI - test: cargo test --all-features --no-fail-fast on Linux - build: cargo build --release --locked across ubuntu-latest / macos-latest / windows-latest, fail-fast disabled so we see all platform issues at once Swatinem/rust-cache@v2 caches ~/.cargo/{registry,git} + target/ between runs to keep CI cycle time reasonable. CARGO_INCREMENTAL=0 because incremental compilation is wasted in a fresh-checkout CI run. Source touched only by `cargo fmt --all` (no behavior changes); the workflow is the substantive add. Co-Authored-By: Claude Opus 4.7 (1M context) --- .github/workflows/ci.yml | 62 ++++++++++++++++++++++++++++++++++++++++ src/api.rs | 4 +-- src/auth/mod.rs | 5 +++- src/auth/tests.rs | 45 +++++++++++++++++++++++------ src/credentials/mod.rs | 4 ++- 5 files changed, 106 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c9059f4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,62 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-D warnings" + +jobs: + lint: + name: Lint (fmt + clippy) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Rust toolchain + run: rustup update stable && rustup default stable && rustup component add rustfmt clippy + + - uses: Swatinem/rust-cache@v2 + + - name: rustfmt + run: cargo fmt --all -- --check + + - name: clippy + run: cargo clippy --all-targets --all-features + + test: + name: Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Rust toolchain + run: rustup update stable && rustup default stable + + - uses: Swatinem/rust-cache@v2 + + - name: cargo test + run: cargo test --all-features --no-fail-fast + + build: + name: Build (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + + - name: Install Rust toolchain + run: rustup update stable && rustup default stable + + - uses: Swatinem/rust-cache@v2 + + - name: cargo build --release + run: cargo build --release --locked diff --git a/src/api.rs b/src/api.rs index 06390b6..aaf5595 100644 --- a/src/api.rs +++ b/src/api.rs @@ -37,9 +37,7 @@ pub enum ApiError { /// GET /v1/auth/me — returns the authenticated user's identity. pub fn me(api_base: &str, access_token: &str) -> Result { let endpoint = format!("{}/v1/auth/me", api_base.trim_end_matches('/')); - let http = Client::builder() - .timeout(Duration::from_secs(15)) - .build()?; + let http = Client::builder().timeout(Duration::from_secs(15)).build()?; let resp = http .get(&endpoint) diff --git a/src/auth/mod.rs b/src/auth/mod.rs index d013725..964e30c 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -44,7 +44,10 @@ impl Pkce { pub fn generate() -> Result { let verifier = random_b64url(32)?; let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); - Ok(Self { verifier, challenge }) + Ok(Self { + verifier, + challenge, + }) } } diff --git a/src/auth/tests.rs b/src/auth/tests.rs index 996220b..3d89621 100644 --- a/src/auth/tests.rs +++ b/src/auth/tests.rs @@ -22,23 +22,35 @@ fn pkce_unique_across_calls() { #[test] fn authorize_url_carries_required_params() { - let p = Pkce { verifier: "v".into(), challenge: "abc".into() }; + let p = Pkce { + verifier: "v".into(), + challenge: "abc".into(), + }; let raw = authorize_url("https://example.com", "STATE", &p); let u = url::Url::parse(&raw).expect("parse"); assert_eq!(u.path(), "/authorize"); let q: std::collections::HashMap<_, _> = u.query_pairs().into_owned().collect(); assert_eq!(q.get("client_id").map(String::as_str), Some(CLIENT_ID)); - assert_eq!(q.get("redirect_uri").map(String::as_str), Some(REDIRECT_URI)); + assert_eq!( + q.get("redirect_uri").map(String::as_str), + Some(REDIRECT_URI) + ); assert_eq!(q.get("response_type").map(String::as_str), Some("code")); assert_eq!(q.get("code_challenge").map(String::as_str), Some("abc")); - assert_eq!(q.get("code_challenge_method").map(String::as_str), Some("S256")); + assert_eq!( + q.get("code_challenge_method").map(String::as_str), + Some("S256") + ); assert_eq!(q.get("state").map(String::as_str), Some("STATE")); } #[test] fn authorize_url_trims_trailing_slash() { - let p = Pkce { verifier: "v".into(), challenge: "c".into() }; + let p = Pkce { + verifier: "v".into(), + challenge: "c".into(), + }; let raw = authorize_url("https://example.com/", "s", &p); assert!( raw.starts_with("https://example.com/authorize?"), @@ -79,7 +91,10 @@ mod exchange { ) .create(); - let pkce = Pkce { verifier: "VERIFIER".into(), challenge: "C".into() }; + let pkce = Pkce { + verifier: "VERIFIER".into(), + challenge: "C".into(), + }; let tr = exchange_code(&http(), &server.url(), "AUTHCODE", &pkce).expect("ok"); m.assert(); assert_eq!(tr.access_token, "AT"); @@ -106,7 +121,10 @@ mod exchange { &http(), &server.url(), "X", - &Pkce { verifier: "v".into(), challenge: "c".into() }, + &Pkce { + verifier: "v".into(), + challenge: "c".into(), + }, ) .unwrap_err(); let actual = format!("{err:?}"); @@ -130,7 +148,10 @@ mod exchange { &http(), &server.url(), "X", - &Pkce { verifier: "v".into(), challenge: "c".into() }, + &Pkce { + verifier: "v".into(), + challenge: "c".into(), + }, ) .unwrap_err(); assert!(matches!(err, AuthError::Server { .. }), "got {err:?}"); @@ -149,9 +170,15 @@ mod exchange { &http(), &server.url(), "X", - &Pkce { verifier: "v".into(), challenge: "c".into() }, + &Pkce { + verifier: "v".into(), + challenge: "c".into(), + }, ) .unwrap_err(); - assert!(matches!(err, AuthError::Other { ref code, .. } if code == "made_up"), "got {err:?}"); + assert!( + matches!(err, AuthError::Other { ref code, .. } if code == "made_up"), + "got {err:?}" + ); } } diff --git a/src/credentials/mod.rs b/src/credentials/mod.rs index beb1f56..016637a 100644 --- a/src/credentials/mod.rs +++ b/src/credentials/mod.rs @@ -50,7 +50,9 @@ pub fn save(creds: &Credentials) -> Result<()> { let mut tmp = NamedTempFile::new_in(parent).context("credentials: tempfile")?; let json = serde_json::to_vec_pretty(creds).context("credentials: encode")?; - tmp.as_file_mut().write_all(&json).context("credentials: write")?; + tmp.as_file_mut() + .write_all(&json) + .context("credentials: write")?; tmp.as_file_mut().flush().context("credentials: flush")?; #[cfg(unix)]