diff --git a/src-tauri/src/account.rs b/src-tauri/src/account.rs index 43801fd9..514bd532 100644 --- a/src-tauri/src/account.rs +++ b/src-tauri/src/account.rs @@ -14,9 +14,11 @@ //! until `valid_until`. Every read of the cache re-verifies the signature, so //! editing the file grants nothing. //! -//! Existing customers: an activated `license.json` keeps working with or without -//! an account (see `combine`), and the device trial still applies to anyone who -//! is not signed in. +//! Stroke 3 has no license keys and no device trial: the signed-in account is +//! the only source of Pro. A license bought with the account's email makes it +//! Pro; every other account gets one trial (`X-Stroke-Trial: account-v3`, a +//! fresh one for v3), then the free plan. A `license.json` left by 2.x stays on +//! disk, untouched and unread, so going back to 2.x still works. use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use ed25519_dalek::{Signature, Verifier, VerifyingKey}; @@ -37,8 +39,6 @@ const DEFAULT_BASE: &str = "https://stroke.click"; /// Vault entry holding the desktop session token. const TOKEN_KEY: &str = "__stroke_account_token__"; const CACHE_FILE: &str = "account.json"; -/// Present while a new install still has to sign in (or enter a key). -const ONBOARDING_FILE: &str = ".account-onboarding"; const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(300); /// Base URL of the website/API. `STROKE_API_BASE` overrides it for local dev. @@ -239,12 +239,6 @@ struct CacheFile { /// The `/api/me` body, verbatim. me: String, fetched_at: u64, - /// SHA-256 of the license key already sent to `/api/license/link`. - #[serde(default)] - linked_key_hash: Option, - /// Why linking failed in a way retrying won't fix (`key_owned_elsewhere`). - #[serde(default)] - link_error: Option, /// The device that wrote this cache. A copy taken to another machine is /// ignored there, which has to sign in for itself. #[serde(default)] @@ -315,24 +309,6 @@ pub fn entitlement_status(ent: &Entitlement, email: &str, now: u64) -> LicenseSt LicenseStatus::TrialExpired } -/// Merge the account's verdict into the local (key / device-trial) one. -/// -/// - No fresh account entitlement: the local status, unchanged. -/// - Account grants Pro via a license: that wins. -/// - A valid local `license.json` is never downgraded by the account: Pro. -/// - Otherwise the account decides (its trial, or no Pro), replacing the -/// per-device trial for signed-in users. -pub fn combine(local: LicenseStatus, account: Option) -> LicenseStatus { - match account { - None => local, - Some(acc @ LicenseStatus::Valid { .. }) => acc, - Some(acc) => match local { - LicenseStatus::Valid { .. } => local, - _ => acc, - }, - } -} - /// The account's status from the cache only: no network, no keychain. Used by /// the license commands so existing Pro gates see account entitlements, also /// when stroke.click can't be reached (see `OFFLINE_GRACE_SECS`). @@ -362,64 +338,27 @@ fn local_dev_pro() -> Option { }) } -pub fn apply_account(dir: &Path, local: LicenseStatus) -> LicenseStatus { +/// The license status, from the signed-in account alone. +/// +/// - Signed out, or no usable entitlement: no Pro (the app asks to sign in). +/// - Fresh entitlement, or paid Pro on the offline grace: what it says. +/// - A trial entitlement past its window keeps counting offline until the +/// trial's own signed end, so a trial doesn't stop on a flight. +pub fn license_status(dir: &Path) -> LicenseStatus { if let Some(dev) = local_dev_pro() { return dev; } - if matches!(local, LicenseStatus::Error { .. }) { - return local; - } - // A key bought by another account doesn't make this account Pro: signed - // in as someone else, this device is on the trial (or that account's own - // plan). Signed out, the key works as it always has. - let local = if matches!(local, LicenseStatus::Valid { .. }) && key_owned_by_other_account(dir) { - crate::license::trial_status(dir) - } else { - local - }; - combine(local, account_license_status(dir)) -} - -/// Signed in, and the server said the license key on this device belongs to a -/// different account. Only for the key it said that about: a new key is asked -/// about afresh. -fn key_owned_by_other_account(dir: &Path) -> bool { - let Some(c) = read_cache(dir) else { return false }; - if c.link_error.as_deref() != Some("key_owned_elsewhere") { - return false; - } - if c.device_id.as_deref().is_some_and(|d| d != crate::license::device_id()) { - return false; + if let Some(status) = account_license_status(dir) { + return status; } - let Some(lic) = crate::license::load_license(dir) else { return false }; - c.linked_key_hash.as_deref() == Some(crate::license::key_hash(&lic.key).as_str()) -} - -// ── New-install detection ───────────────────────────────────────────────────── - -/// Record, once per run and before anything writes the trial files, whether -/// this is a brand-new install (no license, no trial ever started). A new -/// install gets a marker that keeps the sign-in screen up across relaunches -/// until the user signs in or enters a key. Existing installs never get one. -pub fn note_install_state(dir: &Path) { - static NOTED: OnceLock<()> = OnceLock::new(); - NOTED.get_or_init(|| { - let fresh = crate::license::load_license(dir).is_none() - && crate::license::local_trial_start(dir).is_none() - && read_cache(dir).is_none(); - if fresh { - let _ = std::fs::create_dir_all(dir); - let _ = std::fs::write(dir.join(ONBOARDING_FILE), b"1"); + if let Some((me, _)) = cached_me(dir) { + let now = crate::license::trusted_now(dir); + let ent = &me.entitlement; + if ent.plan == "pro" && ent.source == "trial" && ent.trial.as_ref().is_some_and(|t| t.ends_at > now) { + return entitlement_status(ent, &me.user.email, now); } - }); -} - -fn onboarding_pending(dir: &Path) -> bool { - dir.join(ONBOARDING_FILE).exists() -} - -fn clear_onboarding(dir: &Path) { - let _ = std::fs::remove_file(dir.join(ONBOARDING_FILE)); + } + LicenseStatus::TrialExpired } // ── HTTP ────────────────────────────────────────────────────────────────────── @@ -537,18 +476,11 @@ async fn me_text(req: reqwest::RequestBuilder) -> Result { resp.text().await.map_err(|e| ApiError::Network(e.to_string())) } -pub async fn fetch_me(base: &str, token: &str) -> Result { - me_text(http().get(format!("{base}/api/me")).bearer_auth(token)).await -} +/// Asks for the v3 account trial: one fresh trial per account, separate from 2.x. +const TRIAL_SCHEME: (&str, &str) = ("X-Stroke-Trial", "account-v3"); -pub async fn link_license(base: &str, token: &str, key: &str) -> Result { - me_text( - http() - .post(format!("{base}/api/license/link")) - .bearer_auth(token) - .json(&serde_json::json!({ "key": key })), - ) - .await +pub async fn fetch_me(base: &str, token: &str) -> Result { + me_text(http().get(format!("{base}/api/me")).bearer_auth(token).header(TRIAL_SCHEME.0, TRIAL_SCHEME.1)).await } pub async fn remote_sign_out(base: &str, token: &str) { @@ -790,21 +722,16 @@ pub struct AccountStatus { pub fetched_at: u64, /// The last refresh couldn't reach the server; showing the cache. pub offline: bool, - /// New install that hasn't signed in or entered a key yet. + /// Not signed in: the app shows the sign-in screen first. pub needs_onboarding: bool, - /// A license.json is present on this device. - pub has_license_key: bool, - pub link_error: Option, pub error: Option, pub manage_url: String, } fn build_status(dir: &Path, signed_in: bool) -> AccountStatus { - let has_license_key = crate::license::load_license(dir).is_some(); let mut s = AccountStatus { signed_in, - has_license_key, - needs_onboarding: !signed_in && !has_license_key && onboarding_pending(dir), + needs_onboarding: !signed_in, manage_url: format!("{}/app", base_url()), ..Default::default() }; @@ -817,23 +744,19 @@ fn build_status(dir: &Path, signed_in: bool) -> AccountStatus { s.entitlement = Some(me.entitlement); s.devices = me.devices; s.fetched_at = c.fetched_at; - s.link_error = c.link_error; } } s } -/// Save a verified `/api/me` reply, keeping the link bookkeeping. +/// Save a verified `/api/me` reply. fn save_me(dir: &Path, raw: String) -> Result { let me = parse_me(&raw)?; - let prev = read_cache(dir).unwrap_or_default(); write_cache( dir, &CacheFile { me: raw, fetched_at: now_secs(), - linked_key_hash: prev.linked_key_hash, - link_error: prev.link_error, device_id: Some(crate::license::device_id()), }, )?; @@ -843,36 +766,6 @@ fn save_me(dir: &Path, raw: String) -> Result { Ok(me) } -/// Link the held license key to the account, once per key. -async fn link_held_key(dir: &Path, base: &str, token: &str) { - let Some(lic) = crate::license::load_license(dir) else { return }; - let hash = crate::license::key_hash(&lic.key); - let Some(cache) = read_cache(dir) else { return }; - if cache.linked_key_hash.as_deref() == Some(hash.as_str()) { - return; - } - let result = link_license(base, token, &lic.key).await; - let mut c = read_cache(dir).unwrap_or(cache); - match result { - Ok(raw) if parse_me(&raw).is_ok() => { - c.me = raw; - c.fetched_at = now_secs(); - c.linked_key_hash = Some(hash); - c.link_error = None; - } - // Retrying won't change these: remember and stop asking. - Err(ApiError::Server(code, _)) - if matches!(code.as_str(), "key_owned_elsewhere" | "not_found" | "invalid_key" | "revoked") => - { - c.linked_key_hash = Some(hash); - c.link_error = Some(code); - } - // Offline, 5xx, a bad reply: try again on the next refresh. - _ => return, - } - let _ = write_cache(dir, &c); -} - fn data_dir(app: &tauri::AppHandle) -> Result { app.path().app_data_dir().map_err(|e| e.to_string()) } @@ -883,10 +776,7 @@ async fn refresh(app: &tauri::AppHandle, dir: &Path, token: &str) -> AccountStat let base = base_url(); match fetch_me(&base, token).await { Ok(raw) => match save_me(dir, raw) { - Ok(_) => { - link_held_key(dir, &base, token).await; - build_status(dir, true) - } + Ok(_) => build_status(dir, true), Err(e) => AccountStatus { error: Some(e), ..build_status(dir, true) }, }, Err(ApiError::Unauthorized) => { @@ -1020,7 +910,6 @@ async fn sign_in_loopback( .await .map_err(|e| e.user_message())?; store_token(app, tok.token.clone()).await?; - clear_onboarding(dir); Ok(refresh(app, dir, &tok.token).await) } @@ -1051,7 +940,6 @@ pub async fn account_paste_code(app: tauri::AppHandle, text: String) -> Result) -> Result { let dir = data_dir(&app)?; - note_install_state(&dir); let token = load_token(&app).await; Ok(match token { Some(t) if refresh.unwrap_or(false) => self::refresh(&app, &dir, &t).await, @@ -1092,13 +979,6 @@ pub async fn account_sign_out(app: tauri::AppHandle) -> Result Result<(), String> { - clear_onboarding(&data_dir(&app)?); - Ok(()) -} - // ── Tests ───────────────────────────────────────────────────────────────────── #[cfg(test)] @@ -1285,23 +1165,6 @@ mod tests { assert!(matches!(entitlement_status(&ent("free", "none", 9e9 as u64), "a", now), LicenseStatus::TrialExpired)); } - #[test] - fn existing_keys_are_never_downgraded() { - let key = LicenseStatus::Valid { email: "k@x".into(), plan: "pro".into(), issued_at: 1, expires_at: None }; - let device_trial = LicenseStatus::Trial { days_remaining: 5 }; - // No account: unchanged. - assert!(matches!(combine(key.clone(), None), LicenseStatus::Valid { .. })); - assert!(matches!(combine(device_trial.clone(), None), LicenseStatus::Trial { days_remaining: 5 })); - // Account says free: the key still grants Pro. - assert!(matches!(combine(key.clone(), Some(LicenseStatus::TrialExpired)), LicenseStatus::Valid { .. })); - assert!(matches!(combine(key, Some(LicenseStatus::Trial { days_remaining: 2 })), LicenseStatus::Valid { .. })); - // Account Pro lifts an expired device trial. - let acc = LicenseStatus::Valid { email: "a".into(), plan: "pro".into(), issued_at: 1, expires_at: None }; - assert!(matches!(combine(LicenseStatus::TrialExpired, Some(acc)), LicenseStatus::Valid { .. })); - // Signed in: the account's trial replaces the device trial. - assert!(matches!(combine(device_trial, Some(LicenseStatus::Trial { days_remaining: 9 })), LicenseStatus::Trial { days_remaining: 9 })); - } - #[test] fn sign_in_params_match_server_rules() { let (_, c) = pkce_pair(); @@ -1338,7 +1201,7 @@ mod tests { .await .unwrap(); assert_eq!(page.status(), 200); - assert!(page.text().await.unwrap().contains("return to Stroke")); + assert!(page.text().await.unwrap().contains("Head back to Stroke")); assert_eq!(waiter.await.unwrap(), Ok("c0de".to_string())); // Cancel from the website. @@ -1399,7 +1262,6 @@ mod tests { let base = mock_server(vec![ ("POST /api/desktop/token", 200, r#"{"token":"tok","user":{"id":"u1","email":"a@b.co","name":"A","image":null}}"#.into()), ("GET /api/me", 200, me.clone()), - ("POST /api/license/link", 409, r#"{"error":"key_owned_elsewhere","message":"Owned by another account"}"#.into()), ]) .await; @@ -1412,10 +1274,6 @@ mod tests { assert!(parse_me_with_key(&raw, &sk.verifying_key()).is_ok()); assert_eq!(fetch_me(&base, "wrong").await, Err(ApiError::Unauthorized)); - assert_eq!( - link_license(&base, "tok", "k").await, - Err(ApiError::Server("key_owned_elsewhere".into(), "Owned by another account".into())) - ); let bad = mock_server(vec![("POST /api/desktop/token", 400, r#"{"error":"expired_code","message":"x"}"#.into())]).await; let e = exchange_code(&bad, "c", "v", "d", "n", "1.0").await.unwrap_err(); diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index a2eeedf5..b9cdbf06 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1856,170 +1856,19 @@ pub fn connections_store_write(app: tauri::AppHandle, json: String) -> Result<() // ── License ─────────────────────────────────────────────────────────────────── -// `async` so the first call (device-fingerprint subprocess + trial-file I/O) -// runs off the main thread instead of blocking the UI during startup. +// `async` so the first call (device fingerprint, cache read) runs off the main +// thread instead of blocking the UI during startup. Pro comes from the +// signed-in account only (see account::license_status). #[tauri::command(async)] pub fn check_license_status(app: tauri::AppHandle) -> crate::license::LicenseStatus { match app.path().app_data_dir() { - Ok(dir) => { - // Before check_status starts a trial, so a new install is told apart. - crate::account::note_install_state(&dir); - crate::account::apply_account(&dir, crate::license::check_status(&dir)) - } + Ok(dir) => crate::account::license_status(&dir), Err(e) => crate::license::LicenseStatus::Error { message: e.to_string(), }, } } -#[tauri::command] -pub async fn activate_license( - app: tauri::AppHandle, - key: String, -) -> Result { - // 1. Verify signature locally (works offline, catches forged keys) - let parsed = crate::license::verify_key(&key)?; - let device_id = crate::license::device_id(); - - // 2. Register with server. Blocks on seat_limit_exceeded / revoked. - // On network failure api_activate returns Ok(None) - we allow offline activation. - match crate::license::api_activate(&key, &device_id, &app.package_info().version.to_string()).await { - Ok(None) => {} // offline - proceed with local-only activation - Ok(Some(_)) => {} // server accepted - Err(e) => { - // Convert server error codes to user-friendly messages - let msg = match e.as_str() { - "seat_limit_exceeded" => "This license is on all the devices it covers. Remove one at stroke.click/app, or ask for more devices there (\"Need more devices?\").", - "revoked" => "This license key has been revoked.", - "expired" => "This license key has expired.", - "not_found" => "License key not found.", - _ => return Err(e), - }; - return Err(msg.to_string()); - } - } - - // 3. Save locally - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - let lic = crate::license::LicenseFile { - version: 1, - key, - email: parsed.email.clone(), - plan: parsed.plan.clone(), - issued_at: parsed.issued_at, - expires_at: parsed.expires_at, - device_id, - activated_at: now, - last_check_at: now, - }; - crate::license::save_license(&dir, &lic)?; - Ok(serde_json::json!({ - "email": parsed.email, - "plan": parsed.plan, - "issued_at": parsed.issued_at, - "expires_at": parsed.expires_at, - })) -} - -#[tauri::command] -pub async fn deactivate_license(app: tauri::AppHandle) -> Result<(), String> { - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - // Best-effort server deactivation (release the seat) - if let Some(lic) = crate::license::load_license(&dir) { - crate::license::api_deactivate(&lic.key, &lic.device_id).await; - } - crate::license::delete_license(&dir) -} - -/// Validates the license against the server on every launch. -/// - valid: true → update last_check_at, return Valid -/// - revoked / expired → delete local license, return Trial/TrialExpired -/// - device_not_activated → re-activate this device, keep the license -/// - any other error or network failure → keep the license (local signature -/// is the grace; the next launch checks again) -/// - no license → local trial check only (no network call) -#[tauri::command] -pub async fn run_license_check( - app: tauri::AppHandle, -) -> crate::license::LicenseStatus { - let dir = match app.path().app_data_dir() { - Ok(d) => d, - Err(e) => return crate::license::LicenseStatus::Error { message: e.to_string() }, - }; - crate::account::note_install_state(&dir); - - if let Some(mut lic) = crate::license::load_license(&dir) { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); - - use crate::license::CheckOutcome; - let version = app.package_info().version.to_string(); - let mut ended = false; - match crate::license::api_check(&lic.key, &lic.device_id, &version).await { - Some(CheckOutcome::Valid) => { - lic.last_check_at = now; - let _ = crate::license::save_license(&dir, &lic); - } - Some(CheckOutcome::Ended) => ended = true, - Some(CheckOutcome::NotActivated) => { - // Activated offline, so the server never saw this device (or its - // seat was released). Register it now rather than dropping Pro. - match crate::license::api_activate(&lic.key, &lic.device_id, &version).await { - Ok(Some(_)) => { - lic.last_check_at = now; - let _ = crate::license::save_license(&dir, &lic); - } - Err(e) if e == "revoked" || e == "expired" => ended = true, - // Offline, seat limit, or anything else: keep the key and - // try again on the next check. - _ => {} - } - } - // `not_found`, unknown errors, a bad deploy, or offline: keep the key; - // the local signature is the grace. - Some(CheckOutcome::Unknown) | None => {} - } - if ended { - let _ = crate::license::delete_license(&dir); - } - } - - // No valid paid license → reconcile the trial clock with the server so a - // reinstall/disk-wipe can't grant a fresh trial (server keeps the earliest - // start per device). Silent no-op when offline. - if crate::license::load_license(&dir).is_none() { - crate::license::reconcile_trial(&dir).await; - } - - // A signed-in account's cached, signature-checked entitlement can grant Pro; - // it never takes Pro away from a valid key (see account::combine). - crate::account::apply_account(&dir, crate::license::check_status(&dir)) -} - -// ── License debug helpers (debug builds only) ───────────────────────────────── - -/// Backdate the trial file so the UI shows it as expired (or N days elapsed). -/// Only compiled in debug mode - stripped from release builds entirely. -#[cfg(debug_assertions)] -#[tauri::command] -pub fn debug_set_trial_days_ago(app: tauri::AppHandle, days_ago: u64) -> Result<(), String> { - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - crate::license::debug_set_trial_days_ago(&dir, days_ago) -} - -#[cfg(debug_assertions)] -#[tauri::command] -pub fn debug_reset_trial(app: tauri::AppHandle) -> Result<(), String> { - let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - crate::license::debug_reset_trial(&dir) -} - // ── Sample database ──────────────────────────────────────────────────────────── /// Ensures the bundled sample SQLite database exists in the app data directory. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ba20942c..e620ba5a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -902,14 +902,10 @@ pub fn run() { db::terminal::terminal_install_client, db::terminal::terminal_close, commands::check_license_status, - commands::activate_license, - commands::deactivate_license, - commands::run_license_check, account::account_sign_in, account::account_cancel_sign_in, account::account_status, account::account_sign_out, - account::account_skip_onboarding, account::account_paste_code, sync::sync_state, sync::sync_setup, @@ -939,10 +935,6 @@ pub fn run() { db::parked::close_parked, db::parked::parked_connections, commands::export_parquet, - #[cfg(debug_assertions)] - commands::debug_set_trial_days_ago, - #[cfg(debug_assertions)] - commands::debug_reset_trial, ]) .build(tauri::generate_context!()) .expect("error while running tauri application") diff --git a/src-tauri/src/license.rs b/src-tauri/src/license.rs index 9f23919f..8e669f46 100644 --- a/src-tauri/src/license.rs +++ b/src-tauri/src/license.rs @@ -1,101 +1,38 @@ -/// License system - Ed25519 signed keys + a TRIAL_DAYS-day trial. +/// Licensing primitives shared by the account code (`account.rs`). /// -/// Key format: . -/// Message: "v1:{email}:{plan}:{iat}:{exp}" (UTF-8, exp=0 means lifetime) -/// -/// After first activation the decoded data is written to: -/// /license.json -/// -/// Trial is tracked in TWO locations (8 LE bytes = u64 unix timestamp of first launch): -/// /.trial - removed on a full uninstall -/// /.stroke/trial - survives uninstall, so reinstalling does NOT -/// grant a fresh trial. The earliest timestamp -/// across both wins, and both are repaired on read. -/// (For tamper-proof enforcement across full disk wipes, register the trial -/// start server-side keyed by device_id - the API scaffolding already exists.) -/// -/// ------------------------------------------------------------------- -/// SETUP: run `node scripts/license-tool.mjs keygen` once. -/// Copy the printed public key hex into PUBLIC_KEY_HEX below, then rebuild. -/// ------------------------------------------------------------------- -use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; -use ed25519_dalek::{Signature, Verifier, VerifyingKey}; +/// Stroke 3 has no license keys and no device trial: Pro comes from the +/// signed-in account's signed entitlement. What is left here is the status the +/// UI reads, the key that verifies entitlements, the clock guard and the device +/// fingerprint. use sha2::{Digest, Sha256}; use std::{ path::{Path, PathBuf}, time::{SystemTime, UNIX_EPOCH}, }; -const STROKE_API: &str = "https://stroke.click/api/license"; - -// ── Generated by `node scripts/license-tool.mjs keygen` ───────────────────── +/// Ed25519 public key that signs account entitlements on stroke.click. pub const PUBLIC_KEY_HEX: &str = "b5f14fed4694302a767e32c4e6a50ba0074c4e50f5198ad781de00d0e8ba8771"; -pub const TRIAL_DAYS: i64 = 17; -const LICENSE_FILE: &str = "license.json"; -const TRIAL_FILE: &str = ".trial"; - -// ── Revocation list ─────────────────────────────────────────────────────────── -// Each entry is the hex-encoded SHA-256 of the full license key string. -// To revoke a key: -// 1. Run: node scripts/license-tool.mjs revoke -// 2. Copy the printed hash into this array. -// 3. Rebuild and ship an app update. -// -// Note: revocation only takes effect after the user installs the update. -// For immediate remote revocation you'll need the server endpoint (coming later). -const REVOKED_KEY_HASHES: &[&str] = &[ - "ed13c9edc3bea01c6f82a415a10b21f85b85f829004f473cb78e8cd10056059f", // revoked 2026-06-05 (case: LIC-REV-2026-06-05-01) -]; - -// ── Data types ──────────────────────────────────────────────────────────────── - -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] -pub struct LicenseFile { - pub version: u8, - /// The raw key string the user pasted in - pub key: String, - pub email: String, - pub plan: String, - pub issued_at: u64, - /// None / missing field → lifetime license - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_at: Option, - pub device_id: String, - pub activated_at: u64, - /// Unix timestamp of the last successful server check (0 = never checked). - #[serde(default)] - pub last_check_at: u64, -} - #[derive(serde::Serialize, Debug, Clone)] #[serde(tag = "status")] pub enum LicenseStatus { - /// Active paid license + /// Paid Pro on the account Valid { email: String, plan: String, issued_at: u64, expires_at: Option, }, - /// Free trial still running + /// The account's free trial is running Trial { days_remaining: i64 }, - /// Trial period over, no license + /// No Pro: trial over, free plan, or signed out TrialExpired, /// App data dir inaccessible (should not normally happen) Error { message: String }, } -// ── Path helpers ────────────────────────────────────────────────────────────── - -pub fn license_path(data_dir: &Path) -> PathBuf { - data_dir.join(LICENSE_FILE) -} - -pub fn trial_path(data_dir: &Path) -> PathBuf { - data_dir.join(TRIAL_FILE) -} +// ── Paths ───────────────────────────────────────────────────────────────────── /// The user's home directory, cross-platform (HOME on unix/macOS, USERPROFILE on Windows). fn home_dir() -> Option { @@ -104,22 +41,12 @@ fn home_dir() -> Option { .map(PathBuf::from) } -/// All locations the trial start is mirrored to. The app-data copy is wiped on -/// uninstall; the home-dir copy survives, so a reinstall can't reset the trial. -fn trial_paths(data_dir: &Path) -> Vec { - let mut paths = vec![trial_path(data_dir)]; - if let Some(home) = home_dir() { - paths.push(home.join(".stroke").join("trial")); - } - paths -} - // ── Clock guard ─────────────────────────────────────────────────────────────── // // Offline, every expiry check compares against the system clock - and setting // the clock back would stretch a trial or a cached entitlement for as long as // the machine stays off the network. The latest time the app has ever seen is -// kept (mirrored like the trial start, so deleting one copy changes nothing), +// kept (in two places, so deleting one copy changes nothing), // and offline checks use whichever is later: the clock, or that mark. Winding // the clock back then gains nothing. A successful server check resets the mark // to the server's own time, so a clock that was wrong in the future direction @@ -252,7 +179,7 @@ fn machine_id_raw() -> String { .unwrap_or_else(|_| "unknown-host".to_string()) } -// ── Trial management ────────────────────────────────────────────────────────── +// ── Time ────────────────────────────────────────────────────────────────────── fn now_secs() -> u64 { SystemTime::now() @@ -260,411 +187,3 @@ fn now_secs() -> u64 { .map(|d| d.as_secs()) .unwrap_or(0) } - -/// Reads the trial start across all mirror locations and returns `days_remaining` -/// (negative = expired). The EARLIEST timestamp found wins - so deleting one copy -/// (e.g. uninstalling, which wipes app-data) can't grant a fresh trial while the -/// home-dir copy survives. Every location is (re)written with the winning start so -/// a missing/newer copy is repaired on each launch. -pub fn trial_days_remaining(data_dir: &Path) -> i64 { - let paths = trial_paths(data_dir); - - let mut earliest: Option = None; - for p in &paths { - if let Ok(bytes) = std::fs::read(p) { - if let Ok(arr) = <[u8; 8]>::try_from(bytes.as_slice()) { - let t = u64::from_le_bytes(arr); - earliest = Some(earliest.map_or(t, |e| e.min(t))); - } - } - } - - // First launch on this device (or every copy was removed) - start now. - let start_secs = earliest.unwrap_or_else(now_secs); - - // Propagate/repair the winning start to every location. - for p in &paths { - if let Some(dir) = p.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = std::fs::write(p, start_secs.to_le_bytes()); - } - - let elapsed_days = (trusted_now(data_dir).saturating_sub(start_secs) / 86_400) as i64; - TRIAL_DAYS - elapsed_days -} - -/// The earliest trial start recorded across local mirrors, without writing. -/// `None` if no local trial file exists yet (e.g. a fresh install). -pub(crate) fn local_trial_start(data_dir: &Path) -> Option { - let mut earliest: Option = None; - for p in trial_paths(data_dir) { - if let Ok(bytes) = std::fs::read(&p) { - if let Ok(arr) = <[u8; 8]>::try_from(bytes.as_slice()) { - let t = u64::from_le_bytes(arr); - earliest = Some(earliest.map_or(t, |e| e.min(t))); - } - } - } - earliest -} - -/// Phone home to sync the trial clock with the server (earliest-wins). The -/// server records the start the first time it sees this device and always -/// returns the earliest known start - so a reinstall or disk wipe can't hand -/// out a fresh trial. On success the authoritative start is written to every -/// local mirror so the next local check reflects it. No-op when offline. -pub async fn reconcile_trial(data_dir: &Path) { - let local = local_trial_start(data_dir); - if let Some(server_start) = api_trial(&device_id(), local).await { - for p in trial_paths(data_dir) { - if let Some(dir) = p.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = std::fs::write(&p, server_start.to_le_bytes()); - } - } -} - -/// DEBUG ONLY - write a trial start timestamp N days in the past so the UI -/// shows "N days elapsed" without waiting for real time to pass. -#[cfg(debug_assertions)] -pub fn debug_set_trial_days_ago(data_dir: &Path, days_ago: u64) -> Result<(), String> { - let fake_start = now_secs().saturating_sub(days_ago * 86_400); - for p in trial_paths(data_dir) { - if let Some(dir) = p.parent() { - std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; - } - std::fs::write(&p, fake_start.to_le_bytes()).map_err(|e| e.to_string())?; - } - Ok(()) -} - -/// DEBUG ONLY - delete every trial mirror so the next check starts a fresh trial. -#[cfg(debug_assertions)] -pub fn debug_reset_trial(data_dir: &Path) -> Result<(), String> { - for p in trial_paths(data_dir) { - if p.exists() { - std::fs::remove_file(&p).map_err(|e| e.to_string())?; - } - } - Ok(()) -} - -// ── Signature verification ──────────────────────────────────────────────────── - -#[derive(Debug)] -pub struct ParsedKey { - pub email: String, - pub plan: String, - pub issued_at: u64, - pub expires_at: Option, -} - -/// Return the hex SHA-256 of a key string - used to populate REVOKED_KEY_HASHES. -pub fn key_hash(key: &str) -> String { - let mut h = Sha256::new(); - h.update(key.as_bytes()); - hex::encode(h.finalize()) -} - -/// Verify an `.` license key. -/// Returns the parsed payload on success, or an error string. -pub fn verify_key(key: &str) -> Result { - // Check revocation list first - let hash = key_hash(key); - if REVOKED_KEY_HASHES.contains(&hash.as_str()) { - return Err("this license key has been revoked".to_string()); - } - - // Decode public key - let pk_bytes: [u8; 32] = hex::decode(PUBLIC_KEY_HEX) - .map_err(|_| "invalid public key constant (not hex)".to_string())? - .try_into() - .map_err(|_| "public key must be 32 bytes".to_string())?; - - // Reject placeholder key - if pk_bytes == [0u8; 32] { - return Err("Public key not configured - run `node scripts/license-tool.mjs keygen` and update PUBLIC_KEY_HEX in license.rs".to_string()); - } - - let verifying_key = - VerifyingKey::from_bytes(&pk_bytes).map_err(|e| format!("bad public key: {e}"))?; - - // Split key into message + signature - let (msg_b64, sig_b64) = key - .split_once('.') - .ok_or_else(|| "invalid key format (expected .)".to_string())?; - - let msg_bytes = URL_SAFE_NO_PAD - .decode(msg_b64.trim()) - .map_err(|_| "key payload is not valid base64url".to_string())?; - - let sig_bytes = URL_SAFE_NO_PAD - .decode(sig_b64.trim()) - .map_err(|_| "key signature is not valid base64url".to_string())?; - - let sig_arr: [u8; 64] = sig_bytes - .try_into() - .map_err(|_| "signature must be 64 bytes".to_string())?; - let signature = Signature::from_bytes(&sig_arr); - - // Verify Ed25519 signature - verifying_key - .verify(&msg_bytes, &signature) - .map_err(|_| "invalid license signature - key may be forged or corrupted".to_string())?; - - // Parse message "v1:{email}:{plan}:{iat}:{exp}" - let msg_str = String::from_utf8(msg_bytes) - .map_err(|_| "message payload is not UTF-8".to_string())?; - - let parts: Vec<&str> = msg_str.splitn(5, ':').collect(); - if parts.len() != 5 || parts[0] != "v1" { - return Err("unrecognised license message format".to_string()); - } - - let email = parts[1].to_string(); - let plan = parts[2].to_string(); - let iat: u64 = parts[3] - .parse() - .map_err(|_| "invalid issued_at timestamp".to_string())?; - let exp_raw: u64 = parts[4] - .parse() - .map_err(|_| "invalid expires_at timestamp".to_string())?; - let expires_at = if exp_raw == 0 { None } else { Some(exp_raw) }; - - // Check expiry - if let Some(exp) = expires_at { - if now_secs() > exp { - return Err("license has expired".to_string()); - } - } - - Ok(ParsedKey { - email, - plan, - issued_at: iat, - expires_at, - }) -} - -// ── License file I/O ────────────────────────────────────────────────────────── - -pub fn load_license(data_dir: &Path) -> Option { - let raw = std::fs::read_to_string(license_path(data_dir)).ok()?; - serde_json::from_str(&raw).ok() -} - -pub fn save_license(data_dir: &Path, lic: &LicenseFile) -> Result<(), String> { - std::fs::create_dir_all(data_dir).map_err(|e| e.to_string())?; - let json = serde_json::to_string_pretty(lic).map_err(|e| e.to_string())?; - std::fs::write(license_path(data_dir), json).map_err(|e| e.to_string()) -} - -pub fn delete_license(data_dir: &Path) -> Result<(), String> { - let p = license_path(data_dir); - if p.exists() { - std::fs::remove_file(p).map_err(|e| e.to_string())?; - } - Ok(()) -} - -// ── Hostname helper ─────────────────────────────────────────────────────────── - -fn hostname() -> String { - std::env::var("COMPUTERNAME") - .or_else(|_| std::env::var("HOSTNAME")) - .or_else(|_| std::fs::read_to_string("/etc/hostname").map(|s| s.trim().to_string())) - .unwrap_or_else(|_| "unknown".to_string()) -} - -// ── Remote API calls ────────────────────────────────────────────────────────── - -fn http_client() -> &'static reqwest::Client { - static LICENSE_CLIENT: std::sync::OnceLock = std::sync::OnceLock::new(); - LICENSE_CLIENT.get_or_init(|| { - reqwest::Client::builder() - // 4s, not 10s. This call is fire-and-forget - it only catches server-side - // revocation, and a network failure already falls through to the offline - // grace path. On a flaky uplink the old timeout meant a request hanging - // around for ten seconds (visible as a 10s run_license_check in the - // waterfall) to reach a conclusion it was going to reach anyway. - .timeout(std::time::Duration::from_secs(4)) - .build() - .unwrap_or_default() - }) -} - -/// POST /api/license/activate - registers this device with the server. -/// Returns the server JSON on success, or an error string. -/// On network failure returns Ok(None) so the caller can apply an offline grace. -pub async fn api_activate( - key: &str, - device_id: &str, - app_version: &str, -) -> Result, String> { - let body = serde_json::json!({ - "key": key, - "device_id": device_id, - "hostname": hostname(), - // Shown next to the device on the account dashboard. - "os": std::env::consts::OS, - "version": app_version, - }); - let resp = match http_client() - .post(format!("{STROKE_API}/activate")) - .json(&body) - .send() - .await - { - Ok(r) => r, - Err(_) => return Ok(None), // network unreachable → offline grace - }; - let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?; - if json.get("valid").and_then(|v| v.as_bool()).unwrap_or(false) { - Ok(Some(json)) - } else { - let err = json - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown_error") - .to_string(); - Err(err) - } -} - -/// What `/api/license/check` said about this key on this device. -#[derive(Debug, PartialEq)] -pub enum CheckOutcome { - Valid, - /// `revoked` or `expired`: the key is finished, drop it. - Ended, - /// The device was never registered (offline activation) or its seat was - /// released: register it again. - NotActivated, - /// Any other answer (`not_found`, a server bug, a bad deploy). Keep the key; - /// the local signature still holds and the next check tries again. - Unknown, -} - -pub fn check_outcome(json: &serde_json::Value) -> CheckOutcome { - if json.get("valid").and_then(|v| v.as_bool()) == Some(true) { - return CheckOutcome::Valid; - } - match json.get("error").and_then(|v| v.as_str()) { - Some("revoked" | "expired") => CheckOutcome::Ended, - Some("device_not_activated") => CheckOutcome::NotActivated, - _ => CheckOutcome::Unknown, - } -} - -/// POST /api/license/check - phone-home to detect server-side revocation. -/// Returns `None` on network error or an unreadable reply (retry later). -pub async fn api_check(key: &str, device_id: &str, app_version: &str) -> Option { - let body = serde_json::json!({ - "key": key, - "device_id": device_id, - "os": std::env::consts::OS, - "version": app_version, - }); - let resp = http_client() - .post(format!("{STROKE_API}/check")) - .json(&body) - .send() - .await - .ok()?; - let json: serde_json::Value = resp.json().await.ok()?; - Some(check_outcome(&json)) -} - -/// POST /api/license/trial - register/sync this device's trial start. -/// Sends the local start (if any) so the server can keep the earliest; returns -/// the server's authoritative start (unix seconds), or None on network error. -pub async fn api_trial(device_id: &str, local_started_at: Option) -> Option { - let mut body = serde_json::json!({ "device_id": device_id, "hostname": hostname() }); - if let Some(s) = local_started_at { - body["started_at"] = serde_json::json!(s); - } - let resp = http_client() - .post(format!("{STROKE_API}/trial")) - .json(&body) - .send() - .await - .ok()?; - let json: serde_json::Value = resp.json().await.ok()?; - json.get("started_at").and_then(|v| v.as_u64()) -} - -/// POST /api/license/deactivate - releases the seat on the server. -/// Fire-and-forget; silently ignores errors. -pub async fn api_deactivate(key: &str, device_id: &str) { - let body = serde_json::json!({ "key": key, "device_id": device_id }); - let _ = http_client() - .post(format!("{STROKE_API}/deactivate")) - .json(&body) - .send() - .await; -} - -// ── High-level status check ─────────────────────────────────────────────────── - -pub fn check_status(data_dir: &Path) -> LicenseStatus { - // 1. Valid stored license? - if let Some(lic) = load_license(data_dir) { - // Re-verify signature and device binding - match verify_key(&lic.key) { - Ok(parsed) => { - // Soft device check - if lic.device_id == device_id() || cfg!(debug_assertions) { - return LicenseStatus::Valid { - email: parsed.email, - plan: parsed.plan, - issued_at: parsed.issued_at, - expires_at: parsed.expires_at, - }; - } - // Device mismatch - treat as expired trial so they can re-activate - } - Err(_) => { - // Corrupted / tampered license file - remove it - let _ = delete_license(data_dir); - } - } - } - - // 2. Trial - trial_status(data_dir) -} - -/// The trial's state alone, ignoring any license key on this device. -pub fn trial_status(data_dir: &Path) -> LicenseStatus { - let days = trial_days_remaining(data_dir); - if days > 0 { - LicenseStatus::Trial { - days_remaining: days, - } - } else { - LicenseStatus::TrialExpired - } -} - -#[cfg(test)] -mod check_outcome_tests { - use super::*; - use serde_json::json; - - #[test] - fn only_revoked_or_expired_end_the_key() { - assert_eq!(check_outcome(&json!({"valid": true})), CheckOutcome::Valid); - assert_eq!(check_outcome(&json!({"valid": false, "error": "revoked"})), CheckOutcome::Ended); - assert_eq!(check_outcome(&json!({"valid": false, "error": "expired"})), CheckOutcome::Ended); - assert_eq!( - check_outcome(&json!({"valid": false, "error": "device_not_activated"})), - CheckOutcome::NotActivated - ); - for e in ["not_found", "bad_signature", "missing_fields", "something_new"] { - assert_eq!(check_outcome(&json!({"valid": false, "error": e})), CheckOutcome::Unknown); - } - assert_eq!(check_outcome(&json!({"oops": 1})), CheckOutcome::Unknown); - } -} diff --git a/src/App.svelte b/src/App.svelte index 4a38efa1..0d4a5395 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -29,18 +29,16 @@ void installClipboardBridge() // Dev-only console helpers (window.__TAURI__ isn't exposed without - // withGlobalTauri, which we keep off in production). Debug trial commands - // only exist in debug builds, so these are dev-only too. + // withGlobalTauri, which we keep off in production). if (import.meta.env.DEV) { const { invoke } = await import('@tauri-apps/api/core') const { refreshLicenseStatus } = await import('$lib/stores/license.js') // @ts-expect-error - dev-only debug surface window.__stroke = { status: () => invoke('check_license_status'), - resetTrial: async () => { await invoke('debug_reset_trial'); return refreshLicenseStatus() }, - expireTrial: async (daysAgo = 20) => { await invoke('debug_set_trial_days_ago', { daysAgo }); return refreshLicenseStatus() }, + refresh: () => refreshLicenseStatus(), } - console.info('[stroke] dev helpers → window.__stroke.status() / .expireTrial(20) / .resetTrial()') + console.info('[stroke] dev helpers → window.__stroke.status() / .refresh()') } // Suppress Tauri's internal "Couldn't find callback id" warning. diff --git a/src/lib/components/AboutDialog.svelte b/src/lib/components/AboutDialog.svelte index 845d7114..fb451dcd 100644 --- a/src/lib/components/AboutDialog.svelte +++ b/src/lib/components/AboutDialog.svelte @@ -1,20 +1,15 @@ @@ -54,20 +41,17 @@ - +
{#if !$licenseStatus}
- Checking license… + Checking your plan…
{:else if isValid} - -
Plan
@@ -76,78 +60,24 @@ · {$licenseStatus.expires_at ? `until ${new Date($licenseStatus.expires_at * 1000).toLocaleDateString()}` : 'Lifetime'}
-
Licensed to
+
Account
{$licenseStatus.email}
- {:else if isTrial} - -
-
- - - - {$licenseStatus.days_remaining}d left - -
- {#if showActivate} - { showActivate = false; open = false }} /> - - {:else} - - {/if} +
+ + + + {$licenseStatus.days_remaining}d left +
{:else} - -
-
-

No active license

-

Free features only.

-
- {#if showActivate} - { showActivate = false; open = false }} /> - - {:else} - - {/if} +
+

No Stroke Pro on this account

+

Free features only.

{/if}
diff --git a/src/lib/components/AccountCard.svelte b/src/lib/components/AccountCard.svelte index 7ab2fb83..c4f65373 100644 --- a/src/lib/components/AccountCard.svelte +++ b/src/lib/components/AccountCard.svelte @@ -26,13 +26,6 @@ const devices = $derived($account?.devices?.length ?? 0) let signingOut = $state(false) - const LINK_ERRORS = /** @type {Record} */ ({ - key_owned_elsewhere: 'The license on this device was bought with another account, so this account is on the free trial. Sign in with the account that bought it to use it here.', - revoked: 'The license key on this device has been revoked.', - not_found: 'The license key on this device was not found on the server.', - invalid_key: 'The license key on this device could not be linked.', - }) - async function handleSignOut() { if (signingOut) return signingOut = true @@ -80,17 +73,12 @@
- {#if $account?.link_error} -

{LINK_ERRORS[$account.link_error] ?? 'The license key on this device could not be linked.'}

- {/if} {:else}

Stroke account

- {$account?.has_license_key - ? 'Your key keeps working. Sign in to sync connections across devices.' - : 'Your license and trial come with you to every device you sign in on.'} + Stroke Pro and the trial come with you to every device you sign in on.

{#if idle} @@ -123,9 +111,6 @@

{devices} {devices === 1 ? 'device' : 'devices'} signed in{#if $account?.offline}. Offline, showing the last saved plan{/if}.

- {#if $account?.link_error} -

{LINK_ERRORS[$account.link_error] ?? 'The license key on this device could not be linked.'}

- {/if}
-{/snippet} - -
- {#if !compact && !naked && !inline} -
-

Enter your license key

-

Sent to your email after purchase.

-
- {/if} - - - {#if inline} -
- {@render keyField('flex-1 min-w-0')} - {@render submitBtn(false, 'Activate')} -
- {:else} - {@render keyField('')} - {/if} - - -
-
-

- - {shownError} -

-
-
- - {#if !inline} - {@render submitBtn(true, 'Activate')} - {/if} -
- -{#if success} - -{/if} diff --git a/src/lib/components/LicenseGate.svelte b/src/lib/components/LicenseGate.svelte index 15985c1b..1febb02e 100644 --- a/src/lib/components/LicenseGate.svelte +++ b/src/lib/components/LicenseGate.svelte @@ -1,30 +1,35 @@ -{#if $needsOnboarding && !onboardingDone} - +{#if !ready} + +{:else if $needsOnboarding && !onboardingDone} + (onboardingDone = true)} /> {#if import.meta.env.DEV && tourPreview} {#await import('./Onboarding.svelte') then { default: Onboarding }} @@ -63,7 +67,7 @@ {/await} {/if} {:else if $isBlocked || holdGate} - + (holdGate = false)} /> {:else} {@render children()} diff --git a/src/lib/components/LicensePage.svelte b/src/lib/components/LicensePage.svelte index 4dd75009..017afa2b 100644 --- a/src/lib/components/LicensePage.svelte +++ b/src/lib/components/LicensePage.svelte @@ -1,6 +1,5 @@