Compare commits

..

1 Commits

Author SHA1 Message Date
Brandon Thomas 08dfb8515f Added new models and modes: GPT Image 2.5, Wan, Output Formats 2026-09-18 16:10:26 -04:00
366 changed files with 3056 additions and 10784 deletions

View File

@ -44,7 +44,6 @@ explicitly authorizes a cache cleanup.
- Prefer `use` imports over inline fully-qualified paths; only qualify inline for true one-offs or std collisions
- TypeScript with Nx, React, Vite, Zustand, and Three.js
- Use two spaces for indentation
- Each Tauri command belongs in its own file module, named after the command. Keep shared state, types, and helpers in separate support modules; see the [Storyteller command conventions](crates/desktop/artcraft/src/services/storyteller/commands/AGENTS.md).
### File Layout

9
Cargo.lock generated
View File

@ -262,7 +262,6 @@ version = "0.0.1"
dependencies = [
"anyhow",
"artcraft_api_defs",
"artcraft_client_identity",
"backoff",
"chrono",
"cloudflare_errors",
@ -283,13 +282,6 @@ dependencies = [
"uuid_utils",
]
[[package]]
name = "artcraft_client_identity"
version = "0.0.1"
dependencies = [
"url",
]
[[package]]
name = "artcraft_router"
version = "0.0.1"
@ -7026,7 +7018,6 @@ dependencies = [
name = "tauri-plugin-http"
version = "2.4.3"
dependencies = [
"artcraft_client_identity",
"bytes",
"cookie_store 0.21.1",
"data-url",

View File

@ -16,7 +16,6 @@ members = [
"crates/api_clients/worldlabs_api_client",
"crates/api_clients/worldlabs_consumer_client",
"crates/desktop/artcraft",
"crates/lib/artcraft_client_identity",
"crates/lib/browser_emulation",
"crates/lib/build_metadata",
"crates/lib/caching/memory_store",
@ -50,7 +49,6 @@ publish = false
[workspace.dependencies]
artcraft_api_defs = { path = "crates/api_clients/artcraft/artcraft_api_defs" }
artcraft_client = { path = "crates/api_clients/artcraft/artcraft_client" }
artcraft_client_identity = { path = "crates/lib/artcraft_client_identity" }
artcraft_router = { path = "crates/api_clients/artcraft/artcraft_router" }
browser_emulation = { path = "crates/lib/browser_emulation" }
cookie_store_wrapper = { path = "crates/lib/cookie_store_wrapper" }

View File

@ -1,177 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 ArtCraft Team and the ArtCraft contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

86
LICENSE.md Normal file
View File

@ -0,0 +1,86 @@
ArtCraft License (WIP)
======================
(**Warning**: This isn't a real lawyery license full of legitimate legalese yet, but we'll take care of that ASAP.)
ArtCraft is a form of "fair source" software. It's like [free beer](https://en.wiktionary.org/wiki/free_as_in_beer)
in that we give you the code, but there are a few small limitations on what you can do with it.
First, what you *can* do with ArtCraft:
> 1. You do not have to pay us to use ArtCraft. It's free.
>
> 2. You can back up, copy, modify, compile, and use the code for your own private personal purposes.
>
> 3. You can do anything you want with the media you create with ArtCraft. Generated assets are yours.
What you *can't do* with ArtCraft:
> 1. You cannot sell the ArtCraft software commercially (eg. as your own software).
>
> 2. You cannot use the ArtCraft code to develop a competing business or product (eg. selling AI image and video tools).
>
> 3. You cannot fork ArtCraft and remove ArtCraft community, donation links, or paid model services. We intend to
> make money to improve ArtCraft for everyone.
>
> 4. You cannot use the ArtCraft name, logo, or mascot characters to promote your business without permission.
This license means you can see what we're doing and not be at risk of having the rug pulled out from under
you (eg. if our founders die, if our business collapses, if zombies or space aliens invade). It also gives
you a really great way to customize the software or lend a hand in reporting (or even fixing) bugs.
Our desire is to support artists, designers, and filmmakers. We want to help you build your own creative studios
and businesses. We want to give you creative software you can use forever.
ArtCraft is free. We do offer models available through us where you can pay us and support our development, but we also
offer the ability for you to use other providers - and we'll keep adding more options so you have maximum flexibility.
## Our Promise
- All development and business plans will be communicated openly with the community.
- Except for minor test scripts or a few small places where we might need to use licensed 3rd party code, all of
our engineering efforts will live in a single publicly available monorepo. You can see everything we do and even
benefit from using it for personal use. We plan on building a lot more than what you see today, and you'll get
all of it.
- We will not "rug pull" our users. If our business shuts down, gets acquired, or otherwise changes, the tools
we create will always continue to function in the same way.
- If the business ends and our founders quit working in this space, we'll make it so the software transitions
to an OSI-approved open source license. (We don't intend to quit!)
## Why not OSI Open Source?
Philosophical answer: The OSI is an industry body led by hyperscalers. They poach from open source all the time, yet
hyperscaler systems and code (AWS, GCP, YouTube, etc.) remain closed source. The tiniest nuggets are open, but the vast
machinery surrounding it - systems, user behaviors, funnels, at-scale moneymakers - is totally closed.
Practical answer: OSI licenses make it exceptionally challenging to grow big things commercially. And many of
the licenses leave room for hyperscalers to reach in and cherry-pick pieces for themselves that they can better
commercialize than the original authors.
Then there's completely open source software that doesn't even attempt to be a business.
We love software like Blender, but (1) developing ArtCraft is our full-time job, (2) we want to build something at scale
that is much bigger than what you presently see, and (3) this will eventually become much more capital intensive than
just writing code - we want to train novel models that work directly in conjunction with the user interface.
If and when we do get to scale, we intend to keep every bit of our work in the open, including the models. Available
for use, inspection, learning, fitting onto consumer GPU hardware, and more.
Not having a way to make money is unfortunately what killed Stability.ai. Stability.ai walked so that others could
eventually run. (Black Forest Labs, et al.) We're not egotistical enough to count ourselves in that party yet, but we
believe in the original Stability.ai ethos and that their model can work with a few tweaks.
We want to build big and incredible tools the world hasn't seen before. We want to keep them free and entirely source
available. You don't have to pay us, but if you do, all of your investment goes right back into the engineering
and the tools. We're writing code you can clone and keep.
## Inspiration
We took inspiration for this from [Fair Source](https://fair.io/), [Fair Code](https://faircode.io/),
the [Defold License](https://defold.com/license/), and Hacker News discussions. The folks at Obsidian
have some pretty good thoughts on this as well.
~ Brandon Thomas

48
NOTICE
View File

@ -1,48 +0,0 @@
ArtCraft
Copyright (c) 2026 ArtCraft Team and the ArtCraft contributors.
Licensed under the MIT License or the Apache License, Version 2.0, at your option
(LICENSE-MIT, LICENSE-APACHE).
The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team. They are not covered
by the license above.
Third-party material
This product bundles third-party material under its own licenses, listed below.
ammo.js (frontend/apps/artcraft/app/public/jsm/libs/ammo.wasm.*) — zlib License. A port of the
Bullet Physics engine. https://github.com/kripken/ammo.js
tauri-plugin-http (crates/vendor/tauri-plugin-http/) — MIT or Apache-2.0. Copyright (c) 2017 -
Present Tauri Apps Contributors; Copyright 2019-2023 Tauri Programme within The Commons
Conservancy. Modified fork; see that directory's LICENSE_MIT and LICENSE_APACHE-2.0.
normalize.css v8.0.1 (frontend/apps/artcraft/app/src/styles/normalize.css) — MIT License.
Copyright (c) Nicolas Gallagher and Jonathan Neal. https://github.com/necolas/normalize.css
three-dots v0.3.2 (portion of frontend/apps/artcraft/app/src/styles/base.css) — MIT License.
Copyright (c) 2018 nzbin. https://nzbin.github.io/three-dots/
Font Awesome Free icons (frontend/libs/icons/src/lib/brand-icons.tsx,
frontend/apps/artcraft/app/public/resources/images/services/generic.svg) — CC BY 4.0.
Copyright Fonticons, Inc. https://fontawesome.com/license/free
Carter One font (frontend/apps/artcraft/app/public/resources/fonts/CarterOneRegular.json) —
SIL Open Font License 1.1. https://fonts.google.com/specimen/Carter+One
Third-party trademarks
The AI provider and service logos in frontend/apps/artcraft/app/public/resources/images/services/
are trademarks of their respective owners. They are used only to identify those services and are
not covered by the license above.
Material not covered by the license above
The following files are owned by third parties. They are not licensed under MIT or Apache-2.0,
and no rights to them are granted by this repository. They remain the property of their
respective owners. These assets will be phased out of ArtCraft over time.
frontend/apps/artcraft/app/public/resources/sound/ — sound effects from Nintendo games (Golden
Sun, Metroid Prime, The Legend of Zelda: Ocarina of Time, Super Mario RPG).
frontend/apps/artcraft/app/public/resources/memes/ — meme images and likenesses owned by their
respective rights holders.
frontend/apps/artcraft/app/public/resources/skybox/gray/ and skybox/night/ — skybox textures
from a third-party asset pack.
frontend/apps/artcraft/app/public/resources/pose/Lumine Idle cycle.vmd — third-party MMD motion
data.
frontend/apps/artcraft/app/public/resources/characters_gif/ — renders of Mixamo animations.

View File

@ -136,10 +136,4 @@ Additional provider integrations are planned for Kling, Google, Runway, and Luma
- [Developer documentation](./_docs)
- [Desktop build and development scripts](./script/artcraft)
- [Roadmap](./ROADMAP.md)
- [License](#license)
## License
ArtCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.
Copyright (c) 2026 ArtCraft Team and the ArtCraft contributors. Required notices, including
third-party material not covered by this license, are in [NOTICE](NOTICE).
- [License](./LICENSE.md)

View File

@ -9,67 +9,21 @@ To set up the ArtCraft development environment, install the following:
1. [Install Rust](https://doc.rust-lang.org/cargo/getting-started/installation.html).
2. [Install npm](https://nodejs.org/en/download) or [nvm](https://github.com/nvm-sh/nvm). (Node version `v24.13.0` works at time of writing.)
3. The frontend's Nx and Vite dependencies are installed locally with npm; a global Nx installation is not required for the combined Unix launcher.
3. [Install nx](https://nx.dev/docs/getting-started/installation). (Nx version `v22.4.5` works at time of writing.)
4. [Install Tauri CLI](https://v2.tauri.app/reference/cli/). (Version `tauri-cli 2.10.0` works at time of writing.)
An easy way to get started with running the app in development is to run the two commands (in separate terminals):
**Mac and Linux Development**
```bash
# Start the frontend and Rust/Tauri together in one terminal
./script/artcraft/unix_dev.sh
# Run the frontend dev server
./script/artcraft/unix_frontend_dev.sh
# Optionally start the free-port search at another port
ARTCRAFT_DEV_PORT=6200 ./script/artcraft/unix_dev.sh
# Run the Tauri Rust application
./script/artcraft/unix_rust_dev.sh
```
Use the combined launcher instead of starting the two legacy dev scripts. It
works from any working directory when invoked by its path and installs frontend
dependencies if the local Vite installation is missing. Node.js 20+ is required.
The launcher binds Vite to `127.0.0.1`, starting at port **5193** and trying
successive ports until one is available. It leaves existing listeners alone.
Only after the real frontend socket is bound does it start Tauri with that exact
`devUrl`. HTTP and the HMR websocket share the selected port; Rust communicates
through native Tauri IPC and needs no separate HTTP port. Configuration overrides
are passed in memory, without changing the checked-in Tauri config.
The native HTTP bridge normalizes loopback development origins for first-party
API requests so an automatically selected port does not break login or media
loading. See the [desktop session regression checks](../docs/desktop-session-regression.md)
when changing ports, the launcher, or authentication.
JavaScript, TypeScript, React, and CSS changes use Vite hot reload; compatible
React component edits use Fast Refresh. Changes that cannot be hot-replaced
reload the page. Rust changes use `cargo tauri dev`'s automatic **rebuild and app
restart**, including dependent workspace crates. SQLx metadata and SQLite
migrations are also watched. Rust reload is a process restart, so it does not
preserve unsaved in-memory app state. See [Tauri's watch behavior](https://v2.tauri.app/develop/#reacting-to-source-code-changes).
After startup, a Vite configuration restart must reuse the chosen port or report
an error; it cannot silently switch to another port while Tauri uses an old URL.
Ctrl-C stops this session's frontend, Rust watcher/compiler, and desktop app.
If the Rust watcher exits, the launcher closes Vite and propagates the exit code.
It never finds or terminates another app by name or port.
The launcher retains the existing Unix defaults for `VITE_ENVIRONMENT_TYPE`,
`SQLX_OFFLINE`, `RUSTFLAGS`, and the Linux WebKit workarounds. Explicit environment
overrides are preserved. It uses the normal Artcraft app data and Cargo target
directory; port separation does not create an isolated account/data profile, and
concurrent Rust builds can wait on Cargo's build lock.
To verify the launcher without compiling Rust or opening a desktop window:
```bash
node --test frontend/scripts/unix-dev.test.mjs
```
The tests use real Vite listeners and HMR, with a test-owned fake Cargo process
tree. They cover occupied ports, simultaneous launches, React edits, shutdown,
Rust-process failure, and watcher arguments. To verify native Rust reload, run
the launcher, wait for the desktop window, make a Rust source edit, and check for
a rebuild/restart in the same terminal. Frontend edits should update the webview
without restarting the Rust process.
**Windows Development**
```powershell

View File

@ -1,73 +0,0 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Deserialize, Serialize, ToSchema)]
pub struct CreateLoginChallengeRequest {}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct ReviewLoginChallengeRequest {
pub approval_token: String,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct DecideLoginChallengeRequest {
pub approval_token: String,
pub approve: bool,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct PollLoginChallengeRequest {
pub device_token: String,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct CreateLoginChallengeResponse {
pub success: bool,
pub device_token: String,
pub verification_url: String,
pub confirmation_code: String,
pub expires_at: DateTime<Utc>,
pub poll_interval_seconds: u32,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct ReviewLoginChallengeResponse {
pub success: bool,
pub status: LoginChallengeState,
pub maybe_failure_type: Option<LoginChallengeFailure>,
pub confirmation_code: String,
pub requesting_ip: String,
pub expires_at: DateTime<Utc>,
pub username: String,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct LoginChallengeResponse {
pub success: bool,
pub status: LoginChallengeState,
pub maybe_failure_type: Option<LoginChallengeFailure>,
/// Present only to the device after the redemption transaction commits.
#[serde(skip_serializing_if = "Option::is_none")]
pub maybe_signed_session: Option<String>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum LoginChallengeState {
Pending,
Approved,
Redeemed,
Failed,
#[serde(other)]
Unknown,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum LoginChallengeFailure {
UserDeclined,
Expired,
#[serde(other)]
Unknown,
}

View File

@ -2,5 +2,4 @@ pub mod change_password;
pub mod edit_email;
pub mod edit_username;
pub mod login;
pub mod session_info;
pub mod login_challenges;
pub mod session_info;

View File

@ -1,12 +1,11 @@
use crate::common::responses::user_details_light::UserDetailsLight;
use enums::by_table::users::user_feature_flag::UserFeatureFlag;
use serde_derive::{Deserialize, Serialize};
use serde::{Deserialize as DeserializeTrait, Deserializer};
use serde_derive::Serialize;
use std::collections::BTreeSet;
use tokens::tokens::users::UserToken;
use utoipa::ToSchema;
#[derive(Serialize, Deserialize, Copy, Clone, ToSchema)]
#[derive(Serialize, Copy, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum FakeYouPlan {
Free,
@ -15,7 +14,7 @@ pub enum FakeYouPlan {
Pro,
}
#[derive(Serialize, Deserialize, Copy, Clone, ToSchema)]
#[derive(Serialize, Copy, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorytellerStreamPlan {
Free,
@ -24,7 +23,7 @@ pub enum StorytellerStreamPlan {
Pro,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[derive(Serialize, ToSchema)]
pub struct SessionUserInfo {
pub core_info: UserDetailsLight,
@ -42,7 +41,6 @@ pub struct SessionUserInfo {
/// Collection of feature / rollout flags
/// This is the proper place to detect if a user has access to some rollout (non-paywall) feature.
/// NB: The BTreeSet maintains order so React doesn't introduce re-render state bugs when order changes
#[serde(default, deserialize_with = "deserialize_known_feature_flags")]
pub maybe_feature_flags: BTreeSet<UserFeatureFlag>,
// Premium plans:
@ -78,7 +76,7 @@ pub struct SessionUserInfo {
pub can_delete_users: bool,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[derive(Serialize, ToSchema)]
pub struct SessionOnboardingState {
/// If true, the user hasn't set their email.
pub email_not_set: bool,
@ -93,18 +91,9 @@ pub struct SessionOnboardingState {
pub username_not_customized: bool,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[derive(Serialize, ToSchema)]
pub struct SessionInfoSuccessResponse {
pub success: bool,
pub logged_in: bool,
pub user: Option<SessionUserInfo>,
}
// Server rollouts may introduce flags before a desktop release understands them.
// Ignore only unknown flag names; malformed values and authentication fields
// still fail decoding. Unknown flags never grant a client-side capability.
fn deserialize_known_feature_flags<'de, D>(deserializer: D) -> Result<BTreeSet<UserFeatureFlag>, D::Error>
where D: Deserializer<'de> {
let names = Vec::<String>::deserialize(deserializer)?;
Ok(names.into_iter().filter_map(|name| UserFeatureFlag::from_str(&name).ok()).collect())
}

View File

@ -1,27 +0,0 @@
# artcraft_client
Rust HTTP endpoint bindings used by the ArtCraft Tauri desktop app.
## Endpoint layout
- Each HTTP endpoint binding must live in its own descriptively named `.rs` file.
This applies to both free functions and methods implemented on a shared client.
Do not combine several routes into a catch-all file such as `login_challenges.rs`
or `password_auth.rs`.
- Group related bindings in a directory module. Keep `mod.rs` for module declarations;
it must not contain endpoint implementations. For example:
`endpoints/users/login_challenges/create_login_challenge.rs` and
`endpoints/users/login_challenges/poll_login_challenge.rs`.
- Keep each endpoint's route constant, request construction, and endpoint-specific
request/response types in its file. Keep shared wire types in `artcraft_api_defs`
or a dedicated shared type module; do not duplicate them across endpoint files.
- Put shared HTTP transport, client setup, and common error handling in a separate
utility module. A transport module must not accumulate endpoint bindings.
- Update callers to import types from their new modules when splitting bindings.
Preserve request methods, paths, headers, error behavior, and cookie handling.
## Validation
Run `cargo check --offline -p artcraft_client` for client changes. For native login
bindings, also run `SQLX_OFFLINE=true cargo test --offline -p artcraft --lib
login_bridge_tests`; these tests use local HTTP fixtures and temporary cookie jars.

View File

@ -19,7 +19,6 @@ path = "src/lib.rs"
# Internal
artcraft_api_defs.workspace = true
artcraft_client_identity.workspace = true
cloudflare_errors.workspace = true
enums.workspace = true
errors.workspace = true

View File

@ -29,7 +29,7 @@ pub async fn get_media_file(api_host: &ApiHost, media_file_token: &MediaFileToke
debug!("Requesting {:?}", &url);
let response = http_get_anonymous(api_host, url).await?;
let response = http_get_anonymous(url).await?;
let response = filter_bad_response(response).await?;
let response_body = &response.text().await
.map_err(|err| StorytellerError::Api(ApiError::from(err)))?;

View File

@ -3,8 +3,7 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use chrono::{DateTime, Utc};
@ -12,6 +11,7 @@ use enums::common::generation_provider::GenerationProvider;
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -56,7 +56,8 @@ pub async fn legacy_upload_media_file_from_file<P: AsRef<Path>>(
//let mut file = File::open(path)?;
let client = storyteller_client_builder(args.api_host)
let client = Client::builder()
.gzip(true)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
@ -85,6 +86,7 @@ pub async fn legacy_upload_media_file_from_file<P: AsRef<Path>>(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -3,8 +3,7 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use enums::common::generation_provider::GenerationProvider;
@ -12,6 +11,7 @@ use chrono::{DateTime, Utc};
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::fs::File;
use std::io::Read;
@ -72,7 +72,8 @@ pub async fn upload_image_media_file_from_bytes(
debug!("Requesting {:?}", &url);
let client = storyteller_client_builder(args.api_host)
let client = Client::builder()
.gzip(true)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
@ -94,6 +95,7 @@ pub async fn upload_image_media_file_from_bytes(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -3,8 +3,7 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use chrono::{DateTime, Utc};
@ -12,6 +11,7 @@ use enums::common::generation_provider::GenerationProvider;
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -65,7 +65,8 @@ pub async fn upload_image_media_file_from_file_with_idempotency_token<P: AsRef<P
//let mut file = File::open(path)?;
let client = storyteller_client_builder(args.api_host)
let client = Client::builder()
.gzip(true)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
@ -94,6 +95,7 @@ pub async fn upload_image_media_file_from_file_with_idempotency_token<P: AsRef<P
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -1,8 +1,7 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::api_error::ApiError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use enums::common::generation_provider::GenerationProvider;
@ -10,6 +9,7 @@ use chrono::{DateTime, Utc};
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -32,7 +32,8 @@ pub async fn upload_new_engine_asset_from_file<P: AsRef<Path>>(
debug!("Requesting {:?}", &url);
let client = storyteller_client_builder(api_host)
let client = Client::builder()
.gzip(true)
.build()?;
let file_bytes = std::fs::read(path.as_ref())?;
@ -48,6 +49,7 @@ pub async fn upload_new_engine_asset_from_file<P: AsRef<Path>>(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = maybe_creds {

View File

@ -1,8 +1,7 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::api_error::ApiError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use enums::common::generation_provider::GenerationProvider;
@ -10,6 +9,7 @@ use chrono::{DateTime, Utc};
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -58,7 +58,8 @@ pub async fn upload_video_media_file_from_file<P: AsRef<Path>>(
debug!("Requesting {:?}", &url);
let client = storyteller_client_builder(args.api_host)
let client = Client::builder()
.gzip(true)
.build()?;
let file_bytes = std::fs::read(args.path.as_ref())?;
@ -77,6 +78,7 @@ pub async fn upload_video_media_file_from_file<P: AsRef<Path>>(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -7,4 +7,3 @@ pub mod media_files;
pub mod prompts;
pub mod stripe_artcraft;
pub mod subscriptions;
pub mod users;

View File

@ -1,16 +0,0 @@
use artcraft_api_defs::users::login_challenges::{CreateLoginChallengeRequest, CreateLoginChallengeResponse};
use reqwest::Method;
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
pub const CREATE_PATH: &str = "/v1/login_challenges/create";
impl LoginChallengeClient {
pub async fn create(&self) -> Result<CreateLoginChallengeResponse, LoginChallengeClientError> {
let request = self
.request(Method::POST, CREATE_PATH)
.json(&CreateLoginChallengeRequest {});
let (result, _) = self.send(request, CREATE_PATH).await?;
Ok(result)
}
}

View File

@ -1,2 +0,0 @@
pub mod create_login_challenge;
pub mod poll_login_challenge;

View File

@ -1,30 +0,0 @@
use artcraft_api_defs::users::login_challenges::{LoginChallengeResponse, PollLoginChallengeRequest};
use reqwest::Method;
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
pub const POLL_PATH: &str = "/v1/login_challenges/poll";
// Deliberately no Debug/Serialize: the wire result contains a bearer credential.
pub struct PollLoginChallengeResult {
pub response: LoginChallengeResponse,
pub session_set_cookie: Option<String>,
}
impl LoginChallengeClient {
pub async fn poll(
&self,
device_token: &str,
) -> Result<PollLoginChallengeResult, LoginChallengeClientError> {
let request = self
.request(Method::POST, POLL_PATH)
.json(&PollLoginChallengeRequest {
device_token: device_token.to_owned(),
});
let (response, session_set_cookie) = self.send(request, POLL_PATH).await?;
Ok(PollLoginChallengeResult {
response,
session_set_cookie,
})
}
}

View File

@ -1,5 +0,0 @@
pub mod login_challenges;
pub mod password_auth_response;
pub mod password_login;
pub mod password_signup;
pub mod session_info;

View File

@ -1,8 +0,0 @@
use serde::Deserialize;
// No Debug: the response contains a bearer credential.
#[derive(Deserialize)]
pub struct PasswordAuthResponse {
pub success: bool,
pub signed_session: Option<String>,
}

View File

@ -1,20 +0,0 @@
use reqwest::Method;
use serde::{Deserialize, Serialize};
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
use super::password_auth_response::PasswordAuthResponse;
pub const LOGIN_PATH: &str = "/v1/login";
// No Debug: the request contains credentials.
#[derive(Deserialize, Serialize)]
pub struct PasswordLoginRequest {
pub username_or_email: String,
pub password: String,
}
impl LoginChallengeClient {
pub async fn password_login(&self, request: &PasswordLoginRequest) -> Result<(PasswordAuthResponse, Option<String>), LoginChallengeClientError> {
self.send(self.request(Method::POST, LOGIN_PATH).json(request), LOGIN_PATH).await
}
}

View File

@ -1,23 +0,0 @@
use reqwest::Method;
use serde::{Deserialize, Serialize};
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
use super::password_auth_response::PasswordAuthResponse;
pub const SIGNUP_PATH: &str = "/v1/create_account";
// No Debug: the request contains credentials.
#[derive(Deserialize, Serialize)]
pub struct PasswordSignupRequest {
pub username: String,
pub email_address: String,
pub password: String,
pub password_confirmation: String,
pub signup_source: String,
}
impl LoginChallengeClient {
pub async fn password_signup(&self, request: &PasswordSignupRequest) -> Result<(PasswordAuthResponse, Option<String>), LoginChallengeClientError> {
self.send(self.request(Method::POST, SIGNUP_PATH).json(request), SIGNUP_PATH).await
}
}

View File

@ -1,19 +0,0 @@
use artcraft_api_defs::users::session_info::SessionInfoSuccessResponse;
use reqwest::Method;
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
pub const SESSION_PATH: &str = "/v1/session";
impl LoginChallengeClient {
pub async fn session(
&self,
signed_session: &str,
) -> Result<SessionInfoSuccessResponse, LoginChallengeClientError> {
let request = self
.request(Method::GET, SESSION_PATH)
.header("Cookie", format!("session={signed_session}"));
let (result, _) = self.send(request, SESSION_PATH).await?;
Ok(result)
}
}

View File

@ -1,6 +1,4 @@
use artcraft_client_identity::origins::{ARTCRAFT_DESKTOP_DEVELOPMENT_ORIGIN, ARTCRAFT_DESKTOP_ORIGIN};
const HTTP_SCHEME: &str = "http";
const HTTPS_SCHEME: &str = "https";
@ -29,15 +27,6 @@ impl ApiHost {
}
}
/// The `Origin` the desktop client declares to this API.
pub fn request_origin(&self) -> &'static str {
match self {
ApiHost::Storyteller => ARTCRAFT_DESKTOP_ORIGIN,
ApiHost::FakeYou => ARTCRAFT_DESKTOP_ORIGIN,
ApiHost::Localhost { .. } => ARTCRAFT_DESKTOP_DEVELOPMENT_ORIGIN,
}
}
pub fn scheme(&self) -> &'static str {
match self {
ApiHost::Storyteller => HTTPS_SCHEME,

View File

@ -3,10 +3,10 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@ -21,11 +21,13 @@ pub async fn basic_json_delete_request<Req: Serialize, Res: DeserializeOwned>(
info!("DELETE {:?}", &url);
let client = storyteller_client_builder(api_host)
let client = Client::builder()
.gzip(true)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.delete(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON)
.header("Content-Type", APPLICATION_JSON);

View File

@ -3,10 +3,10 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@ -20,11 +20,13 @@ pub async fn basic_json_get_request<Res: DeserializeOwned>(
debug!("Requesting {:?}", &url);
let client = storyteller_client_builder(api_host)
let client = Client::builder()
.gzip(true)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.get(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = maybe_creds {

View File

@ -3,10 +3,10 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@ -30,11 +30,13 @@ pub async fn basic_json_post_request<Req: Serialize, Res: DeserializeOwned>(
info!("Requesting {:?}", &url);
}
let client = storyteller_client_builder(api_host)
let client = Client::builder()
.gzip(true)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON)
.header("Content-Type", APPLICATION_JSON);

View File

@ -3,11 +3,11 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::filter_bad_response::filter_bad_response;
use errors::AnyhowResult;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@ -26,11 +26,13 @@ pub async fn basic_query_string_post_request<Res: DeserializeOwned>(
debug!("Requesting {:?}", &url);
let client = storyteller_client_builder(api_host)
let client = Client::builder()
.gzip(true)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = maybe_creds {

View File

@ -1 +1,4 @@
pub const USER_AGENT: &str = "storyteller-client/1.0";
pub const APPLICATION_JSON : &str = "application/json";

View File

@ -1,12 +1,14 @@
use crate::error::api_error::ApiError;
use crate::utils::api_host::ApiHost;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use reqwest::Client;
const USER_AGENT: &str = "storyteller-client/1.0";
pub async fn http_get_anonymous(api_host: &ApiHost, url: String) -> Result<reqwest::Response, ApiError> {
let client = storyteller_client_builder(api_host)
pub async fn http_get_anonymous(url: String) -> Result<reqwest::Response, ApiError> {
let client = Client::builder()
.gzip(true)
.build()?;
let response = client.get(url)
.header("User-Agent", USER_AGENT)
.header("Accept", "application/json")
//.header("Accept-Encoding", "gzip, deflate, br")
.send()

View File

@ -1,184 +0,0 @@
use std::collections::BTreeMap;
use std::time::Duration;
use log::{info, warn};
use reqwest::header::SET_COOKIE;
use reqwest::{Client, Method, RequestBuilder, Response};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use url::Url;
use crate::utils::api_host::ApiHost;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
/// Rejection bodies are small JSON objects; anything larger is not one of ours.
const MAX_REJECTION_BODY_BYTES: usize = 16 * 1024;
/// Native transport for the session bridge. No request/response bodies, cookies,
/// or challenge credentials are logged, even at debug level. Never follows redirects.
#[derive(Clone)]
pub struct LoginChallengeClient {
client: Client,
api_host: ApiHost,
}
#[derive(Debug)]
pub struct LoginChallengeClientError {
pub status: Option<u16>,
pub message: &'static str,
/// The server's explanation for a non-2xx response, when it sent one.
pub maybe_rejection: Option<LoginRejection>,
}
/// The error fields of a rejected login or signup response, such as
/// `{"error_type":"UsernameTaken","error_fields":{"username":"username is taken"}}`.
/// Only these fields are parsed, so no credential can end up in this struct.
#[derive(Debug, Default, Deserialize)]
pub struct LoginRejection {
pub error_type: Option<String>,
pub error_message: Option<String>,
#[serde(default)]
pub error_fields: BTreeMap<String, String>,
}
impl LoginChallengeClient {
pub fn new(api_host: &ApiHost) -> Result<Self, LoginChallengeClientError> {
let mut builder = storyteller_client_builder(api_host);
if matches!(api_host, ApiHost::Localhost { .. }) {
builder = builder.no_proxy();
}
let client = builder
.timeout(Duration::from_secs(15))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|_| LoginChallengeClientError::invalid("Unable to initialize login client"))?;
Ok(Self {
client,
api_host: api_host.clone(),
})
}
pub fn api_origin(&self) -> String {
self.api_host.to_api_hostname_and_scheme()
}
pub fn api_url(&self) -> Url {
Url::parse(&format!("{}/", self.api_origin())).expect("ApiHost must produce a valid origin")
}
pub fn allows_verification_url(&self, value: &str) -> bool {
let Ok(url) = Url::parse(value) else {
return false;
};
let origin_allowed = match self.api_host {
ApiHost::Localhost { .. } => ["http://localhost:4200", "http://127.0.0.1:4200", "http://localhost:4201", "http://127.0.0.1:4201"]
.contains(&url.origin().ascii_serialization().as_str()),
ApiHost::Storyteller => ["https://app.getartcraft.com", "https://getartcraft.com", "https://www.getartcraft.com"]
.contains(&url.origin().ascii_serialization().as_str()),
ApiHost::FakeYou => false,
};
origin_allowed
&& url.username().is_empty()
&& url.password().is_none()
&& url.path() == "/login/desktop"
&& url.query().is_none()
&& url
.fragment()
.and_then(|f| f.strip_prefix("approval_token="))
.map(|s| {
s.len() == 43
&& s
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
})
.unwrap_or(false)
}
pub(crate) fn request(&self, method: Method, path: &str) -> RequestBuilder {
self
.client
.request(method, format!("{}{path}", self.api_origin()))
.header("Accept", "application/json")
}
pub(crate) async fn send<T: DeserializeOwned>(
&self,
request: RequestBuilder,
path: &str,
) -> Result<(T, Option<String>), LoginChallengeClientError> {
let origin = self.api_origin();
info!("Website login request: origin={} path={}", origin, path);
let response = request.send().await.map_err(|_| {
warn!(
"Website login network failure: origin={} path={}",
origin, path
);
LoginChallengeClientError::invalid("Unable to reach the login server")
})?;
let status = response.status();
if !status.is_success() {
warn!(
"Website login HTTP failure: origin={} path={} status={}",
origin,
path,
status.as_u16()
);
return Err(LoginChallengeClientError {
status: Some(status.as_u16()),
message: "Login server rejected the request",
maybe_rejection: read_rejection(response).await,
});
}
let session_cookie = response
.headers()
.get_all(SET_COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.find(|v| {
cookie::Cookie::parse(*v)
.map(|c| c.name() == "session")
.unwrap_or(false)
})
.map(str::to_owned);
let body = response.json().await.map_err(|_| {
warn!(
"Website login invalid response: origin={} path={}",
origin, path
);
LoginChallengeClientError::invalid("Invalid response from login server")
})?;
Ok((body, session_cookie))
}
}
impl LoginChallengeClientError {
pub fn invalid(message: &'static str) -> Self {
Self {
status: None,
message,
maybe_rejection: None,
}
}
}
impl std::fmt::Display for LoginChallengeClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.status {
Some(status) => write!(f, "{} (HTTP {})", self.message, status),
None => write!(f, "{}", self.message),
}
}
}
impl std::error::Error for LoginChallengeClientError {}
async fn read_rejection(response: Response) -> Option<LoginRejection> {
if response.content_length().is_some_and(|len| len > MAX_REJECTION_BODY_BYTES as u64) {
return None;
}
let body = response.bytes().await.ok()?;
if body.len() > MAX_REJECTION_BODY_BYTES {
return None;
}
serde_json::from_slice(&body).ok()
}

View File

@ -4,8 +4,6 @@ pub mod basic_json_post_request;
pub (crate) mod basic_query_string_post_request;
pub (crate) mod filter_bad_response;
pub (crate) mod http_get_anonymous;
pub (crate) mod storyteller_client_builder;
pub mod api_host;
pub mod constants;
pub mod status_codes;
pub mod login_challenge_client;

View File

@ -1,17 +0,0 @@
use artcraft_client_identity::user_agents::ARTCRAFT_DESKTOP_USER_AGENT;
use reqwest::header::{HeaderMap, HeaderValue, ORIGIN};
use reqwest::{Client, ClientBuilder};
use crate::utils::api_host::ApiHost;
/// Every request to our API is built from this so the desktop client identifies itself
/// consistently (`User-Agent` and `Origin`). Only use it for Storyteller / ArtCraft APIs.
pub(crate) fn storyteller_client_builder(api_host: &ApiHost) -> ClientBuilder {
let mut headers = HeaderMap::new();
headers.insert(ORIGIN, HeaderValue::from_static(api_host.request_origin()));
Client::builder()
.user_agent(ARTCRAFT_DESKTOP_USER_AGENT)
.default_headers(headers)
.gzip(true)
}

View File

@ -1,5 +1,4 @@
# Rust sources and Cargo manifests must remain watched for `cargo tauri dev`.
# Vite owns frontend reloads; build artifacts must not trigger Rust rebuilds.
target/
node_modules/
dist/
# Don't restart the dev server on Rust changes
crates/
Cargo.toml
Cargo.lock

View File

@ -3,7 +3,7 @@ name = "artcraft"
version = "0.0.1"
description = "Artcraft"
authors = ["you"]
license = "MIT OR Apache-2.0"
license = ""
repository = ""
edition = "2021"
rust-version = "1.77.2"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 859 B

After

Width:  |  Height:  |  Size: 1023 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

View File

@ -1,10 +1,10 @@
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::core::state::app_startup_time::AppStartupTime;
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
use anyhow::anyhow;
use chrono::TimeDelta;
use errors::AnyhowResult;
use log::{error, info};
use once_cell::sync::Lazy;
use reqwest::Url;
use artcraft_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
@ -13,13 +13,24 @@ use tauri::{AppHandle, Manager};
use tauri_plugin_http::reqwest_cookie_store::CookieStore;
use tauri_plugin_http::Http;
const AVT_COOKIE_NAME: &str = "visitor";
const SESSION_COOKIE_NAME: &str = "session";
const STORYTELLER_ROOT_COOKIE_URL_STR: &str = "https://api.storyteller.ai/";
static STORYTELLER_ROOT_COOKIE_URL: Lazy<Url> = Lazy::new(|| {
Url::parse(STORYTELLER_ROOT_COOKIE_URL_STR).expect("URL should parse")
});
const AVT_COOKIE_NAME : &str = "visitor";
const SESSION_COOKIE_NAME : &str = "session";
/// There's some kind of race condition that we need to wait for before inspecting cookies.
const RACE_CONDITION_WAIT_TIME: TimeDelta = TimeDelta::milliseconds(5000);
pub async fn persist_storyteller_cookies_task(app: &AppHandle, storyteller_credential_manager: &StorytellerCredentialManager, app_startup_time: &AppStartupTime) -> AnyhowResult<()> {
pub async fn persist_storyteller_cookies_task(
app: &AppHandle,
storyteller_credential_manager: &StorytellerCredentialManager,
app_startup_time: &AppStartupTime,
) -> AnyhowResult<()> {
//if app_startup_time.time_delta_since() < RACE_CONDITION_WAIT_TIME {
// // NB: There's an issue when the "main window thread" inquires about the
// // webview cookies shortly after app startup. When it attempts to dump the
@ -30,30 +41,33 @@ pub async fn persist_storyteller_cookies_task(app: &AppHandle, storyteller_crede
//}
let maybe_http = app.try_state::<Http>();
let http = match maybe_http {
None => {
error!("No HTTP plugin found");
return Err(anyhow!("No HTTP plugin found"));
},
}
Some(http) => http,
};
match http.cookies_jar.store.lock() {
Err(err) => {
error!("Failed to lock cookie jar: {:?}", err);
return Err(anyhow!("Failed to lock cookie jar"));
},
}
Ok(cookie_jar) => {
sync_tauri_credentials(&cookie_jar, storyteller_credential_manager, &storyteller_cookie_url(app)?)?;
},
sync_tauri_credentials(&cookie_jar, storyteller_credential_manager)?;
}
}
Ok(())
}
pub(crate) fn sync_tauri_credentials(cookie_store: &CookieStore, storyteller_credential_manager: &StorytellerCredentialManager, api_url: &Url) -> AnyhowResult<()> {
let current_http_plugin_credentials = get_credentials_from_cookie_store(cookie_store, api_url)?;
fn sync_tauri_credentials(
cookie_store: &CookieStore,
storyteller_credential_manager: &StorytellerCredentialManager,
) -> AnyhowResult<()> {
let current_http_plugin_credentials = get_credentials_from_cookie_store(cookie_store)?;
let mut replace_credentials = true;
@ -64,80 +78,31 @@ pub(crate) fn sync_tauri_credentials(cookie_store: &CookieStore, storyteller_cre
replace_credentials = false;
}
}
if replace_credentials {
info!("Syncing ArtCraft credentials ...");
storyteller_credential_manager.set_credentials(&current_http_plugin_credentials)?;
// NB: tauri-plugin-http stores the credentials on disk, so we can defer to that for now.
//storyteller_credential_manager.persist_all_to_disk()?;
}
Ok(())
}
pub fn get_credentials_from_cookie_store(cookie_jar: &CookieStore, api_url: &Url) -> AnyhowResult<StorytellerCredentialSet> {
pub fn get_credentials_from_cookie_store(cookie_jar: &CookieStore) -> AnyhowResult<StorytellerCredentialSet> {
let mut avt_cookie = None;
let mut session_cookie = None;
// Only cookies applicable to our API origin can become ArtCraft credentials.
for (name, value) in cookie_jar.get_request_values(api_url) {
match name {
AVT_COOKIE_NAME => avt_cookie = Some(StorytellerAvtCookie::new(value.to_owned())),
SESSION_COOKIE_NAME => session_cookie = Some(StorytellerSessionCookie::new(value.to_owned())),
_ => {},
for cookie in cookie_jar.iter_unexpired() {
if let Some(avt) = StorytellerAvtCookie::maybe_from_cookie(&cookie) {
avt_cookie = Some(avt);
} else if let Some(session) = StorytellerSessionCookie::maybe_from_cookie(&cookie) {
session_cookie = Some(session);
}
}
Ok(StorytellerCredentialSet::initialize(avt_cookie, session_cookie))
}
pub(crate) fn storyteller_cookie_url(app: &AppHandle) -> AnyhowResult<Url> {
let config = app.try_state::<AppEnvConfigs>().ok_or_else(|| anyhow!("API configuration unavailable"))?;
Ok(Url::parse(&format!("{}/", config.storyteller_host.to_api_hostname_and_scheme()))?)
}
#[cfg(test)]
mod login_bridge_tests {
use super::*;
use crate::core::state::data_dir::app_data_root::AppDataRoot;
use tauri_plugin_http::reqwest_cookie_store::RawCookie;
#[test]
fn approved_response_cookie_reaches_native_credentials() {
let directory = tempfile::tempdir().unwrap();
let root = AppDataRoot::create_existing(directory.path()).unwrap();
let manager = StorytellerCredentialManager::initialize_empty(&root);
let mut jar = CookieStore::default();
let url = Url::parse("https://api.storyteller.ai/v1/login_challenges/poll").unwrap();
jar.store_response_cookies([RawCookie::parse("session=signed_backend_cookie; Secure; HttpOnly; Path=/; Max-Age=3600").unwrap().into_owned(), RawCookie::parse("visitor=existing_visitor; Secure; Path=/; Max-Age=3600").unwrap().into_owned()].into_iter(), &url);
sync_tauri_credentials(&jar, &manager, &url).unwrap();
let credentials = manager.get_credentials_required().unwrap();
assert_eq!(credentials.session.unwrap().as_str(), "signed_backend_cookie");
assert_eq!(credentials.avt.unwrap().as_str(), "existing_visitor");
// Retrying the same successful poll is idempotent for native credentials too.
sync_tauri_credentials(&jar, &manager, &url).unwrap();
assert_eq!(manager.get_credentials_required().unwrap().session.unwrap().as_str(), "signed_backend_cookie");
}
#[test]
fn unrelated_and_expired_cookies_cannot_become_artcraft_sessions() {
let url = Url::parse("https://api.storyteller.ai/").unwrap();
let mut jar = CookieStore::default();
jar.store_response_cookies([RawCookie::parse("session=unrelated; Path=/; Max-Age=3600").unwrap().into_owned()].into_iter(), &Url::parse("https://unrelated.example/").unwrap());
assert!(get_credentials_from_cookie_store(&jar, &url).unwrap().session.is_none());
jar.store_response_cookies([RawCookie::parse("session=expired; Secure; Path=/; Max-Age=0").unwrap().into_owned()].into_iter(), &url);
assert!(get_credentials_from_cookie_store(&jar, &url).unwrap().session.is_none());
}
#[test]
fn configured_local_api_does_not_import_production_cookies() {
let production = Url::parse("https://api.storyteller.ai/").unwrap();
let local = Url::parse("http://localhost:12345/").unwrap();
let mut jar = CookieStore::default();
jar.store_response_cookies([RawCookie::parse("session=production; Secure; Path=/").unwrap().into_owned()].into_iter(), &production);
assert!(get_credentials_from_cookie_store(&jar, &local).unwrap().session.is_none());
jar.store_response_cookies([RawCookie::parse("session=development; Path=/").unwrap().into_owned()].into_iter(), &local);
assert_eq!(get_credentials_from_cookie_store(&jar, &local).unwrap().session.unwrap().as_str(), "development");
assert_eq!(get_credentials_from_cookie_store(&jar, &production).unwrap().session.unwrap().as_str(), "production");
}
Ok(StorytellerCredentialSet::initialize(
avt_cookie,
session_cookie,
))
}

View File

@ -63,13 +63,6 @@ use crate::services::sora::commands::sora_logout_command::sora_logout_command;
use crate::services::sora::state::sora_credential_manager::SoraCredentialManager;
use crate::services::sora::state::sora_task_queue::SoraTaskQueue;
use crate::services::sora::threads::sora_task_polling::sora_task_polling_thread::sora_task_polling_thread;
use crate::services::storyteller::commands::login_bridge::DesktopLoginBridgeState;
use crate::services::storyteller::commands::storyteller_cancel_login_challenge_command::storyteller_cancel_login_challenge_command;
use crate::services::storyteller::commands::storyteller_create_login_challenge_command::storyteller_create_login_challenge_command;
use crate::services::storyteller::commands::storyteller_get_login_session_command::storyteller_get_login_session_command;
use crate::services::storyteller::commands::storyteller_password_login_command::storyteller_password_login_command;
use crate::services::storyteller::commands::storyteller_password_signup_command::storyteller_password_signup_command;
use crate::services::storyteller::commands::storyteller_poll_login_challenge_command::storyteller_poll_login_challenge_command;
use crate::services::storyteller::commands::storyteller_get_credits_command::storyteller_get_credits_command;
use crate::services::storyteller::commands::storyteller_get_subscription_command::storyteller_get_subscription_command;
use crate::services::storyteller::commands::storyteller_purge_credentials_command::storyteller_purge_credentials_command;
@ -208,7 +201,6 @@ pub fn run() {
})
.manage(app_data_root)
.manage(app_env_configs)
.manage(DesktopLoginBridgeState::default())
.manage(app_preferences)
.manage(artcraft_platform_info)
.manage(artcraft_usage_tracker)
@ -267,12 +259,6 @@ pub fn run() {
set_provider_order_command,
sora_get_credential_info_command,
sora_logout_command,
storyteller_get_login_session_command,
storyteller_password_login_command,
storyteller_password_signup_command,
storyteller_create_login_challenge_command,
storyteller_poll_login_challenge_command,
storyteller_cancel_login_challenge_command,
storyteller_get_credits_command,
storyteller_get_subscription_command,
storyteller_open_credits_purchase_command,

View File

@ -1,17 +0,0 @@
# Tauri Commands
- Put each `#[tauri::command]` function in its own `.rs` file module named after
that command, such as `storyteller_create_login_challenge_command.rs`. Do not
collect multiple commands in a catch-all `*_commands.rs` file.
- Keep `mod.rs` for module declarations. Put shared state, response/error types,
and implementation helpers in separate support modules, with the narrowest
visibility needed by their callers.
- Update the imports used by `tauri::generate_handler!` when moving commands.
Preserve IPC command names and arguments unless changing that contract is
explicitly part of the task.
- Authentication HTTP requests run in Rust through `artcraft_client` endpoint
bindings. The frontend invokes Tauri commands; it does not call the API
directly, and desktop commands do not connect to the backend MySQL database.
- For login bridge changes, run the existing native fixture tests with
`SQLX_OFFLINE=true cargo test --offline -p artcraft --lib login_bridge_tests`.
These tests use loopback HTTP servers and temporary cookie stores.

View File

@ -1,364 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use artcraft_api_defs::users::login_challenges::{LoginChallengeFailure, LoginChallengeState};
use artcraft_api_defs::users::session_info::SessionUserInfo;
use artcraft_client::endpoints::users::password_login::PasswordLoginRequest;
use artcraft_client::endpoints::users::password_signup::PasswordSignupRequest;
use artcraft_client::utils::api_host::ApiHost;
use artcraft_client::utils::login_challenge_client::{
LoginChallengeClient, LoginChallengeClientError,
};
use chrono::{DateTime, Utc};
use log::{info, warn};
use serde::Serialize;
use tauri::{AppHandle, Manager};
use tauri_plugin_http::reqwest_cookie_store::{CookieStoreMutex, RawCookie};
use tauri_plugin_http::Http;
use tokio::sync::Mutex;
use uuid_utils::uuid::generate_random_uuid;
use crate::core::threads::main_window_thread::persist_storyteller_cookies_task::get_credentials_from_cookie_store;
use crate::services::storyteller::commands::password_auth_error_message::password_auth_error_message;
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
const MAX_PENDING_CHALLENGES: usize = 8;
/// All bearer credentials stay in Rust. The UI holds only a local lookup handle.
#[derive(Default)]
pub struct DesktopLoginBridgeState {
pending: Mutex<HashMap<String, PendingChallenge>>,
}
#[derive(Clone)]
struct PendingChallenge {
device_token: String,
expires_at: DateTime<Utc>,
client: LoginChallengeClient,
}
#[derive(Serialize)]
pub struct DesktopLoginChallenge {
pub challenge_id: String,
pub verification_url: String,
pub confirmation_code: String,
pub expires_at: DateTime<Utc>,
pub poll_interval_seconds: u32,
}
#[derive(Serialize)]
pub struct DesktopLoginOutcome {
pub status: LoginChallengeState,
pub maybe_failure_type: Option<LoginChallengeFailure>,
pub maybe_user: Option<SessionUserInfo>,
}
#[derive(Debug, Serialize)]
pub struct DesktopLoginError {
pub status: Option<u16>,
pub message: String,
pub retryable: bool,
}
impl DesktopLoginError {
fn local(message: &str) -> Self {
Self {
status: None,
message: message.to_owned(),
retryable: false,
}
}
pub(super) fn from_client(origin: &str, error: LoginChallengeClientError) -> Self {
warn!(
"Website login failed: origin={} status={:?} reason={}",
origin, error.status, error.message
);
Self {
retryable: is_retryable(&error),
status: error.status,
message: format!("{}: {}", origin, error),
}
}
/// Password login/signup errors are shown to the user verbatim, so they say
/// what went wrong ("That username is already taken.") instead of the host.
fn from_password_auth(origin: &str, error: LoginChallengeClientError, is_signup: bool) -> Self {
warn!(
"Password auth failed: origin={} signup={} status={:?} reason={} error_type={:?}",
origin,
is_signup,
error.status,
error.message,
error.maybe_rejection.as_ref().and_then(|r| r.error_type.as_deref())
);
Self {
retryable: is_retryable(&error),
status: error.status,
message: password_auth_error_message(&error, is_signup),
}
}
}
pub(super) async fn current_login_session(
client: &LoginChallengeClient,
jar: &Arc<CookieStoreMutex>,
) -> Result<Option<SessionUserInfo>, DesktopLoginError> {
let credentials = {
let store = jar
.store
.lock()
.map_err(|_| DesktopLoginError::local("HTTP cookie store unavailable"))?;
get_credentials_from_cookie_store(&store, &client.api_url())
.map_err(|_| DesktopLoginError::local("Unable to read session cookie"))?
};
let Some(signed) = credentials.session else {
return Ok(None);
};
let session = match client.session(signed.as_str()).await {
Ok(session) => session,
Err(error) if error.status == Some(401) => return Ok(None),
Err(error) => return Err(DesktopLoginError::from_client(&client.api_origin(), error)),
};
Ok(
session
.user
.filter(|_| session.success && session.logged_in),
)
}
pub(super) async fn password_auth(
host: &ApiHost,
manager: &StorytellerCredentialManager,
jar: &Arc<CookieStoreMutex>,
login: Option<PasswordLoginRequest>,
signup: Option<PasswordSignupRequest>,
) -> Result<SessionUserInfo, DesktopLoginError> {
let client = LoginChallengeClient::new(host)
.map_err(|e| DesktopLoginError::from_client(&host.to_api_hostname_and_scheme(), e))?;
let is_signup = signup.is_some();
let response = match (login, signup) {
(Some(request), None) => client.password_login(&request).await,
(None, Some(request)) => client.password_signup(&request).await,
_ => return Err(DesktopLoginError::local("Invalid authentication request")),
}
.map_err(|e| DesktopLoginError::from_password_auth(&client.api_origin(), e, is_signup))?;
let (response, cookie) = response;
if !response.success {
return Err(DesktopLoginError::local(
"Sign-in failed. Check your account details and try again.",
));
}
let signed = response
.signed_session
.ok_or_else(|| DesktopLoginError::local("Login server did not issue a session"))?;
let cookie =
cookie.ok_or_else(|| DesktopLoginError::local("Login server did not set a session cookie"))?;
let (cookie, user) = verify_session(&client, &signed, cookie).await?;
install_session_cookie(&client, &signed, cookie, manager, jar)?;
persist_session_cookie(jar).await?;
Ok(user)
}
pub(super) fn http_cookie_jar(app: &AppHandle) -> Result<Arc<CookieStoreMutex>, DesktopLoginError> {
Ok(
app
.try_state::<Http>()
.ok_or_else(|| DesktopLoginError::local("HTTP cookie store unavailable"))?
.cookies_jar
.clone(),
)
}
pub(super) async fn begin_challenge(
host: &ApiHost,
state: &DesktopLoginBridgeState,
) -> Result<DesktopLoginChallenge, DesktopLoginError> {
let client = LoginChallengeClient::new(host)
.map_err(|e| DesktopLoginError::from_client(&host.to_api_hostname_and_scheme(), e))?;
let created = client
.create()
.await
.map_err(|e| DesktopLoginError::from_client(&client.api_origin(), e))?;
if !created.success
|| !client.allows_verification_url(&created.verification_url)
|| created.device_token.len() != 43
|| created.expires_at <= Utc::now()
{
return Err(DesktopLoginError::local(
"Invalid login challenge or website/API environment mismatch",
));
}
let mut pending = state.pending.lock().await;
pending.retain(|_, value| value.expires_at > Utc::now());
if pending.len() >= MAX_PENDING_CHALLENGES {
return Err(DesktopLoginError::local("Too many pending login attempts"));
}
let challenge_id = generate_random_uuid();
pending.insert(
challenge_id.clone(),
PendingChallenge {
device_token: created.device_token,
expires_at: created.expires_at,
client,
},
);
Ok(DesktopLoginChallenge {
challenge_id,
verification_url: created.verification_url,
confirmation_code: created.confirmation_code,
expires_at: created.expires_at,
poll_interval_seconds: created.poll_interval_seconds.max(5),
})
}
pub(super) async fn poll_challenge(
state: &DesktopLoginBridgeState,
manager: &StorytellerCredentialManager,
jar: &Arc<CookieStoreMutex>,
challenge_id: &str,
) -> Result<DesktopLoginOutcome, DesktopLoginError> {
let challenge = {
let mut pending = state.pending.lock().await;
let challenge = pending.get(challenge_id).cloned().ok_or_else(|| {
DesktopLoginError::local("Login attempt was cancelled or is no longer available")
})?;
if challenge.expires_at <= Utc::now() {
pending.remove(challenge_id);
return Ok(expired());
}
challenge
};
let origin = challenge.client.api_origin();
let polled = challenge
.client
.poll(&challenge.device_token)
.await
.map_err(|e| DesktopLoginError::from_client(&origin, e))?;
if !polled.response.success || polled.response.status == LoginChallengeState::Unknown {
return Err(DesktopLoginError::local("Unrecognized login response"));
}
if polled.response.status != LoginChallengeState::Redeemed {
if polled.response.status == LoginChallengeState::Failed {
state.pending.lock().await.remove(challenge_id);
}
return Ok(DesktopLoginOutcome {
status: polled.response.status,
maybe_failure_type: polled.response.maybe_failure_type,
maybe_user: None,
});
}
let signed = polled
.response
.maybe_signed_session
.ok_or_else(|| DesktopLoginError::local("Login server did not issue a session"))?;
let set_cookie = polled
.session_set_cookie
.ok_or_else(|| DesktopLoginError::local("Login server did not set a session cookie"))?;
let (cookie, user) = verify_session(&challenge.client, &signed, set_cookie).await?;
{
let pending = state.pending.lock().await;
// A cancellation during either HTTP request must prevent local installation.
if !pending.contains_key(challenge_id) {
return Err(DesktopLoginError::local("Login attempt was cancelled"));
}
if challenge.expires_at <= Utc::now() {
return Ok(expired());
}
install_session_cookie(&challenge.client, &signed, cookie, manager, jar)?;
}
// Keep the challenge for idempotent IPC retries; it expires on its original deadline.
persist_session_cookie(jar).await?;
info!("Website login complete: origin={}", origin);
Ok(DesktopLoginOutcome {
status: LoginChallengeState::Redeemed,
maybe_failure_type: None,
maybe_user: Some(user),
})
}
pub(super) async fn cancel_challenge(state: &DesktopLoginBridgeState, challenge_id: &str) {
state.pending.lock().await.remove(challenge_id);
}
async fn verify_session(
client: &LoginChallengeClient,
signed: &str,
set_cookie: String,
) -> Result<(RawCookie<'static>, SessionUserInfo), DesktopLoginError> {
let cookie = RawCookie::parse(set_cookie)
.map_err(|_| DesktopLoginError::local("Invalid session cookie"))?
.into_owned();
if cookie.name() != "session" || cookie.value() != signed {
return Err(DesktopLoginError::local(
"Session cookie did not match the redeemed session",
));
}
// Validate on the SAME native API host before publishing any new credentials.
let session = client
.session(&signed)
.await
.map_err(|e| DesktopLoginError::from_client(&client.api_origin(), e))?;
let user = session
.user
.filter(|_| session.success && session.logged_in)
.ok_or_else(|| DesktopLoginError::local("The redeemed session could not authenticate"))?;
Ok((cookie, user))
}
fn install_session_cookie(
client: &LoginChallengeClient,
signed: &str,
cookie: RawCookie<'static>,
manager: &StorytellerCredentialManager,
jar: &Arc<CookieStoreMutex>,
) -> Result<(), DesktopLoginError> {
let mut store = jar
.store
.lock()
.map_err(|_| DesktopLoginError::local("HTTP cookie store unavailable"))?;
let mut candidate = store.clone();
candidate.store_response_cookies([cookie].into_iter(), &client.api_url());
let credentials = get_credentials_from_cookie_store(&candidate, &client.api_url())
.map_err(|_| DesktopLoginError::local("Unable to read session cookie"))?;
if credentials.session.as_ref().map(|c| c.as_str()) != Some(signed) {
return Err(DesktopLoginError::local(
"Session cookie does not apply to the configured API host",
));
}
manager
.set_credentials(&credentials)
.map_err(|_| DesktopLoginError::local("Unable to store native login credentials"))?;
*store = candidate;
Ok(())
}
async fn persist_session_cookie(jar: &Arc<CookieStoreMutex>) -> Result<(), DesktopLoginError> {
let saved = jar
.request_save()
.map_err(|_| DesktopLoginError::local("Unable to persist login cookie"))?;
tokio::task::spawn_blocking(move || saved.recv())
.await
.map_err(|_| DesktopLoginError::local("Unable to persist login cookie"))?
.map_err(|_| DesktopLoginError::local("Unable to persist login cookie"))?;
Ok(())
}
fn expired() -> DesktopLoginOutcome {
DesktopLoginOutcome {
status: LoginChallengeState::Failed,
maybe_failure_type: Some(LoginChallengeFailure::Expired),
maybe_user: None,
}
}
fn is_retryable(error: &LoginChallengeClientError) -> bool {
error
.status
.map(|s| s == 429 || s >= 500)
.unwrap_or(error.message == "Unable to reach the login server")
}
#[cfg(test)]
#[path = "storyteller_login_bridge_tests.rs"]
mod login_bridge_tests;

View File

@ -2,12 +2,4 @@ pub mod storyteller_purge_credentials_command;
pub mod storyteller_get_credits_command;
pub mod storyteller_get_subscription_command;
pub mod stripe_checkout;
pub mod stripe_customer_portal;
pub(crate) mod login_bridge;
mod password_auth_error_message;
pub mod storyteller_cancel_login_challenge_command;
pub mod storyteller_create_login_challenge_command;
pub mod storyteller_get_login_session_command;
pub mod storyteller_password_login_command;
pub mod storyteller_password_signup_command;
pub mod storyteller_poll_login_challenge_command;
pub mod stripe_customer_portal;

View File

@ -1,254 +0,0 @@
use artcraft_client::utils::login_challenge_client::{LoginChallengeClientError, LoginRejection};
/// Signup validation fields, in the order they appear on the form.
const FORM_FIELD_ORDER: [&str; 3] = ["username", "email_address", "password"];
/// Turns a rejected `/v1/login` or `/v1/create_account` call into a sentence a
/// user can act on, e.g. "That username is already taken."
pub(super) fn password_auth_error_message(error: &LoginChallengeClientError, is_signup: bool) -> String {
let Some(status) = error.status else {
return match error.message {
"Unable to reach the login server" => {
"Couldn't reach the ArtCraft servers. Check your internet connection and try again.".to_owned()
}
_ => "Something went wrong while signing in. Please try again.".to_owned(),
};
};
if status == 429 {
return "Too many attempts. Please wait a minute and try again.".to_owned();
}
if status >= 500 {
return "ArtCraft's servers are having trouble right now. Please try again in a few minutes.".to_owned();
}
if let Some(message) = error.maybe_rejection.as_ref().and_then(rejection_message) {
return message;
}
match (status, is_signup) {
(401, false) => "Incorrect username, email, or password.".to_owned(),
(_, true) => "We couldn't create your account. Please check your details and try again.".to_owned(),
(_, false) => "We couldn't sign you in. Please check your details and try again.".to_owned(),
}
}
fn rejection_message(rejection: &LoginRejection) -> Option<String> {
match rejection.error_type.as_deref() {
Some("InvalidCredentials") => return Some("Incorrect username, email, or password.".to_owned()),
Some("AccountNeedsPassword") => {
return Some(
"This account doesn't have a password yet. Sign in through the website, or reset your password.".to_owned(),
)
}
_ => {}
}
let ordered_fields = FORM_FIELD_ORDER
.iter()
.filter_map(|field| rejection.error_fields.get(*field))
.chain(
rejection
.error_fields
.iter()
.filter(|(field, _)| !FORM_FIELD_ORDER.contains(&field.as_str()))
.map(|(_, reason)| reason),
);
let field_messages: Vec<String> = ordered_fields.map(|reason| field_reason_message(reason)).collect();
if !field_messages.is_empty() {
return Some(field_messages.join(" "));
}
match rejection.error_type.as_deref() {
Some("UsernameTaken") => Some(field_reason_message("username is taken")),
Some("EmailTaken") => Some(field_reason_message("email is taken")),
Some("UsernameReserved") => Some(field_reason_message("username is reserved")),
_ => rejection
.error_message
.as_deref()
.filter(|message| !message.trim().is_empty())
.map(sentence),
}
}
/// Server validation reasons are terse lowercase phrases; known ones get a
/// friendlier rewrite, and anything else is shown as a sentence.
fn field_reason_message(reason: &str) -> String {
let friendly = match reason {
"username is taken" => "That username is already taken. Please choose another.",
"username is reserved" | "username contains slurs" => "That username isn't available. Please choose another.",
"username is too short" => "Usernames must be at least 3 characters.",
"username is too long" => "Usernames can be at most 16 characters.",
"invalid username characters" => {
"Usernames can only contain letters, numbers, underscores (_), and hyphens (-)."
}
"email is taken" => "An account with that email already exists. Try logging in instead.",
"invalid email address" => "Please enter a valid email address.",
"password is too short" => "Passwords must be at least 6 characters.",
"passwords do not match" => "Passwords do not match.",
other => return sentence(other),
};
friendly.to_owned()
}
fn sentence(text: &str) -> String {
let text = text.trim();
let mut chars = text.chars();
let mut sentence: String = match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => return String::new(),
};
if !sentence.ends_with(['.', '!', '?']) {
sentence.push('.');
}
sentence
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
mod signup_tests {
use super::*;
#[test]
fn username_taken() {
let error = rejected(400, Some("UsernameTaken"), None, &[("username", "username is taken")]);
assert_eq!(signup_message(&error), "That username is already taken. Please choose another.");
}
#[test]
fn email_taken() {
let error = rejected(400, Some("EmailTaken"), None, &[("email_address", "email is taken")]);
assert_eq!(signup_message(&error), "An account with that email already exists. Try logging in instead.");
}
#[test]
fn reserved_username_without_fields_uses_error_type() {
let error = rejected(400, Some("UsernameReserved"), None, &[]);
assert_eq!(signup_message(&error), "That username isn't available. Please choose another.");
}
#[test]
fn multiple_bad_fields_follow_form_order() {
let error = rejected(
400,
Some("BadInput"),
None,
&[("password", "password is too short"), ("email_address", "invalid email address"), ("username", "invalid username characters")],
);
assert_eq!(
signup_message(&error),
"Usernames can only contain letters, numbers, underscores (_), and hyphens (-). Please enter a valid email address. Passwords must be at least 6 characters."
);
}
#[test]
fn unknown_reason_is_shown_as_a_sentence() {
let error = rejected(400, Some("BadInput"), None, &[("username", "username cannot start with 'user_'")]);
assert_eq!(signup_message(&error), "Username cannot start with 'user_'.");
}
#[test]
fn unparseable_400_gets_generic_signup_message() {
let error = status_only(400);
assert_eq!(signup_message(&error), "We couldn't create your account. Please check your details and try again.");
}
}
mod login_tests {
use super::*;
#[test]
fn invalid_credentials() {
let error = rejected(401, Some("InvalidCredentials"), Some("invalid credentials"), &[]);
assert_eq!(login_message(&error), "Incorrect username, email, or password.");
}
#[test]
fn account_needs_password() {
let error = rejected(401, Some("AccountNeedsPassword"), Some("account was created without a password"), &[]);
assert_eq!(
login_message(&error),
"This account doesn't have a password yet. Sign in through the website, or reset your password."
);
}
#[test]
fn bare_401_is_treated_as_bad_credentials() {
assert_eq!(login_message(&status_only(401)), "Incorrect username, email, or password.");
}
}
mod transport_tests {
use super::*;
#[test]
fn rate_limited() {
assert_eq!(login_message(&status_only(429)), "Too many attempts. Please wait a minute and try again.");
}
#[test]
fn server_error() {
let error = rejected(500, Some("ServerError"), Some("server error"), &[]);
assert_eq!(
signup_message(&error),
"ArtCraft's servers are having trouble right now. Please try again in a few minutes."
);
}
#[test]
fn unreachable() {
let error = LoginChallengeClientError::invalid("Unable to reach the login server");
assert_eq!(
login_message(&error),
"Couldn't reach the ArtCraft servers. Check your internet connection and try again."
);
}
#[test]
fn messages_never_expose_raw_http_details() {
for status in [400, 401, 403, 404, 429, 500, 502] {
for message in [login_message(&status_only(status)), signup_message(&status_only(status))] {
assert!(!message.contains("HTTP"), "{message}");
assert!(!message.contains("Some("), "{message}");
assert!(!message.contains("://"), "{message}");
}
}
}
}
fn login_message(error: &LoginChallengeClientError) -> String {
password_auth_error_message(error, false)
}
fn signup_message(error: &LoginChallengeClientError) -> String {
password_auth_error_message(error, true)
}
fn status_only(status: u16) -> LoginChallengeClientError {
LoginChallengeClientError {
status: Some(status),
message: "Login server rejected the request",
maybe_rejection: None,
}
}
fn rejected(
status: u16,
error_type: Option<&str>,
error_message: Option<&str>,
error_fields: &[(&str, &str)],
) -> LoginChallengeClientError {
LoginChallengeClientError {
maybe_rejection: Some(LoginRejection {
error_type: error_type.map(str::to_owned),
error_message: error_message.map(str::to_owned),
error_fields: error_fields
.iter()
.map(|(field, reason)| (field.to_string(), reason.to_string()))
.collect::<BTreeMap<_, _>>(),
}),
..status_only(status)
}
}
}

View File

@ -1,14 +0,0 @@
use tauri::State;
use crate::services::storyteller::commands::login_bridge::{
cancel_challenge, DesktopLoginBridgeState, DesktopLoginError,
};
#[tauri::command]
pub async fn storyteller_cancel_login_challenge_command(
state: State<'_, DesktopLoginBridgeState>,
challenge_id: String,
) -> Result<(), DesktopLoginError> {
cancel_challenge(&state, &challenge_id).await;
Ok(())
}

View File

@ -1,14 +0,0 @@
use tauri::State;
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::services::storyteller::commands::login_bridge::{
begin_challenge, DesktopLoginBridgeState, DesktopLoginChallenge, DesktopLoginError,
};
#[tauri::command]
pub async fn storyteller_create_login_challenge_command(
config: State<'_, AppEnvConfigs>,
state: State<'_, DesktopLoginBridgeState>,
) -> Result<DesktopLoginChallenge, DesktopLoginError> {
begin_challenge(&config.storyteller_host, &state).await
}

View File

@ -1,19 +0,0 @@
use artcraft_api_defs::users::session_info::SessionUserInfo;
use artcraft_client::utils::login_challenge_client::LoginChallengeClient;
use tauri::{AppHandle, State};
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::services::storyteller::commands::login_bridge::{
current_login_session, http_cookie_jar, DesktopLoginError,
};
#[tauri::command]
pub async fn storyteller_get_login_session_command(
app: AppHandle,
config: State<'_, AppEnvConfigs>,
) -> Result<Option<SessionUserInfo>, DesktopLoginError> {
let client = LoginChallengeClient::new(&config.storyteller_host).map_err(|error| {
DesktopLoginError::from_client(&config.storyteller_host.to_api_hostname_and_scheme(), error)
})?;
current_login_session(&client, &http_cookie_jar(&app)?).await
}

Some files were not shown because too many files have changed in this diff Show More