Skip to main content

silicon_waveform_client/
lib.rs

1//! Stateless, typed Rust client for Silicon Waveform: text to speech and speech to text for
2//! Carbons and Silicons.
3//!
4//! Waveform signs accounts in with [Silicon Accounts](https://accounts.teamofsilicons.com).
5//! This package never asks for a password and never stores anything; you decide where tokens
6//! live (the `waveform` CLI keeps them in a private file under `$SILICON_HOME/.waveform/dir`).
7//!
8//! - [`signin::SignIn`] gets Waveform's tokens for an account as Waveform's public client (no
9//!   app secret): the device flow for Carbons ([`signin::SignIn::start_device`]), a
10//!   short-lived token for Silicons ([`signin::SignIn::exchange_slt`]), refresh and sign-out.
11//! - [`Client`] calls the Waveform API with the account's access token
12//!   ([`Client::with_bearer`]), or, for an app acting for an account, with a Silicon Accounts
13//!   User verification proof ([`Client::with_proof`], scopes `waveform.tts` / `waveform.stt`).
14//! - A Carbon reads and manages the Waveform history, settings, provider keys and Briefcase
15//!   access of the Silicons it is custodian of with [`Client::for_account`]. Nobody runs speech
16//!   as another account.
17//!
18//! ```no_run
19//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
20//! use silicon_waveform_client::{Auth, Client, ExposeSecret as _, TtsRequest, signin::SignIn};
21//!
22//! // A Silicon mints a short-lived token with `silicon-accounts login --app waveform -q`.
23//! let sign_in = SignIn::new(silicon_waveform_client::DEFAULT_ACCOUNTS_URL)?;
24//! let tokens = sign_in.exchange_slt("slt_…").await?;
25//! println!("signed in as {}", tokens.account.label());
26//!
27//! let waveform = Client::new(silicon_waveform_client::DEFAULT_API_URL, Auth::Anonymous)?
28//!     .with_bearer(tokens.access_token.expose_secret());
29//! let request = TtsRequest { text: "Hello, Carbons and Silicons.".into(), ..Default::default() };
30//! let speech = waveform.tts(&request, "greeting-0001").await?;
31//! println!("{}", speech.file_url.or(speech.audio_url).unwrap_or_default());
32//! # Ok(()) }
33//! ```
34//!
35//! Errors are typed ([`Error`]): API failures keep Waveform's
36//! `{"error":{"code","message","hint","reason"}}` body ([`ApiError`]), sign-in failures say
37//! exactly why Silicon Accounts refused ([`signin::SignInError`]).
38
39mod client;
40mod error;
41pub mod signin;
42/// Retired no-ops: Waveform records no telemetry.
43#[deprecated(since = "0.7.0", note = "Waveform records no telemetry")]
44pub mod telemetry;
45mod tts_options;
46mod types;
47
48pub use client::{Auth, Client};
49pub use error::{ApiError, Error, Result};
50pub use secrecy::{ExposeSecret, SecretString};
51pub use tts_options::{
52    ElevenLabsTtsOptions, GeminiTtsOptions, OpenAiTtsOptions, TtsProviderOptions,
53};
54pub use types::*;
55
56/// Waveform's app id at Silicon Accounts. It is also the `client_id` of Waveform's public
57/// client (this package and the CLI) and the `receiving_app` of proofs sent to Waveform.
58pub const APP_ID: &str = "waveform";
59/// The production Waveform API origin.
60pub const DEFAULT_API_URL: &str = "https://api.waveform.teamofsilicons.com";
61/// The production Silicon Accounts origin.
62pub const DEFAULT_ACCOUNTS_URL: &str = "https://accounts.teamofsilicons.com";
63/// Waveform's documentation.
64pub const DOCS_URL: &str = "https://docs.waveform.teamofsilicons.com";
65/// Waveform's source repository (open for issues and pull requests).
66pub const REPOSITORY_URL: &str = "https://github.com/teamofsilicons/silicon-waveform";
67/// How a Carbon signs the CLI in (device flow in the browser).
68pub const CARBON_SIGN_IN: &str = "waveform login";
69/// How a Silicon mints a short-lived token for Waveform.
70pub const SLT_MINT_COMMAND: &str = "silicon-accounts login --app waveform -q";
71/// How a Silicon signs the CLI in.
72pub const SILICON_SIGN_IN: &str =
73    "silicon-accounts login --app waveform -q | waveform login --slt-stdin";
74/// Proof scopes Waveform honours from apps acting for an account.
75pub const PROOF_SCOPES: [&str; 2] = ["waveform.tts", "waveform.stt"];
76/// This package's version.
77pub const VERSION: &str = env!("CARGO_PKG_VERSION");
78
79/// The README's examples compile as doctests, so the guide follows the API.
80#[cfg(doctest)]
81#[doc = include_str!("../README.md")]
82struct ReadmeDoctests;
83
84/// True for a host that is this machine (`localhost`, `*.localhost`, `127.0.0.0/8`, `::1`):
85/// the only hosts plain `http://` is accepted for, because tokens would otherwise travel
86/// unencrypted.
87#[must_use]
88pub fn is_loopback(url: &url::Url) -> bool {
89    match url.host() {
90        Some(url::Host::Domain(domain)) => {
91            let domain = domain.to_ascii_lowercase();
92            domain == "localhost" || domain.ends_with(".localhost")
93        }
94        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
95        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
96        None => false,
97    }
98}
99
100#[cfg(test)]
101mod lib_tests {
102    #[test]
103    fn plain_http_is_recognised_only_for_this_machine() {
104        for (url, loopback) in [
105            ("http://localhost:4161", true),
106            ("http://waveform.localhost", true),
107            ("http://127.0.0.1:4161", true),
108            ("http://127.8.0.1", true),
109            ("http://[::1]:4161", true),
110            ("http://10.0.0.2", false),
111            ("http://api.waveform.teamofsilicons.com", false),
112            ("http://localhost.example.com", false),
113        ] {
114            assert_eq!(
115                super::is_loopback(&url::Url::parse(url).unwrap()),
116                loopback,
117                "{url}"
118            );
119        }
120    }
121}