Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src-tauri/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -697,9 +697,13 @@ pub(crate) async fn load_token(app: &tauri::AppHandle) -> Option<String> {
.filter(|t| !t.is_empty())
}

/// A new sign-in also drops any sync key left on this device: it belonged to
/// whoever was signed in before (possibly another account), and this one
/// unlocks sync with its own passphrase.
async fn store_token(app: &tauri::AppHandle, token: String) -> Result<(), String> {
crate::secrets::update_async(app, move |m| {
m.insert(TOKEN_KEY.to_string(), token);
m.remove(crate::sync::SYNC_KEY_VAULT);
})
.await
}
Expand Down
4 changes: 4 additions & 0 deletions src-tauri/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ fn sync_message(e: ApiError) -> String {
"no_sync_key" => KEY_CHANGED.into(),
"too_many_records" | "invalid_request" | "invalid_json" => format!("The server rejected the sync request ({code})."),
"key_exists" => "Sync is already set up for this account. Unlock it with your passphrase.".into(),
"pro_required" => "pro_required".into(),
"invalid_kind" | "invalid_id" => format!("The server rejected a record: {msg}"),
"404" | "not_found" => "Sync isn't available on the server yet.".into(),
_ => e.user_message(),
Expand Down Expand Up @@ -418,6 +419,8 @@ pub struct SyncState {
pub server_has_key: Option<bool>,
/// The server's key changed (reset on another device): this device was locked.
pub key_changed: bool,
/// The account has no paid Pro: sync isn't part of the trial.
pub pro_required: bool,
pub offline: bool,
pub error: Option<String>,
}
Expand All @@ -441,6 +444,7 @@ pub async fn sync_state(app: tauri::AppHandle) -> Result<SyncState, String> {
}
}
Err(ApiError::Network(_)) => s.offline = true,
Err(ApiError::Server(code, _)) if code == "pro_required" => s.pro_required = true,
Err(e) => s.error = Some(sync_message(e)),
}
Ok(s)
Expand Down
6 changes: 3 additions & 3 deletions src/lib/components/ScheduledBackups.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import * as Dialog from '$lib/components/ui/dialog/index.js'
import SegmentedControl from './SegmentedControl.svelte'
import { isSignedIn, openManageAccount } from '$lib/stores/account.js'
import { hasPro } from '$lib/stores/license.js'
import { hasPaidPro, isTrialActive } from '$lib/stores/license.js'
import {
backupOverview, backupLoadError, runningJobId, refreshBackupJobs, saveBackupJob, patchBackupJob,
deleteBackupJob, saveS3Keys, s3KeysRegion, describeCron, formatBytes, SCHEDULE_DRIVERS,
Expand Down Expand Up @@ -233,8 +233,8 @@

{#if !$isSignedIn}
{@render message('Sign in for scheduled backups', 'They come with Stroke Pro on your account.')}
{:else if !$hasPro || overview?.pro === false}
{@render message('Scheduled backups are a Pro feature', 'Up to 10 databases, to Stroke Cloud or your own S3.', getPro)}
{:else if !$hasPaidPro || overview?.pro === false}
{@render message('Scheduled backups need Stroke Pro', $isTrialActive ? "The free trial doesn't include them. Up to 10 databases, to Stroke Cloud or your own S3." : 'Up to 10 databases, to Stroke Cloud or your own S3.', getPro)}
{:else if !connection}
{@render message('Save this connection first', 'Schedules run on saved connections.')}
{:else if !supported}
Expand Down
10 changes: 10 additions & 0 deletions src/lib/components/SyncSection.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
import LockKeyhole from '@lucide/svelte/icons/lock-keyhole'
import CircleAlert from '@lucide/svelte/icons/circle-alert'
import RotateCcw from '@lucide/svelte/icons/rotate-ccw'
import ExternalLink from '@lucide/svelte/icons/external-link'
import { isTrialActive } from '$lib/stores/license.js'
import { openManageAccount } from '$lib/stores/account.js'

let { sectionLabel = '' } = $props()

Expand Down Expand Up @@ -120,6 +123,13 @@
<p class="text-ui-sm text-muted-foreground">Sign in to sync your workspaces, connections and settings across devices.</p>
{:else if s.phase === 'checking'}
<p class="text-ui-sm text-muted-foreground">Checking sync…</p>
{:else if s.phase === 'pro'}
<div class="flex items-center justify-between gap-3">
<p class="text-ui-sm leading-relaxed text-muted-foreground">
Sync needs Stroke Pro{$isTrialActive ? "; the free trial doesn't include it" : ''}. Workspaces, connections and settings on every device, end-to-end encrypted.
</p>
<Button variant="secondary" size="sm" class="shrink-0" onclick={() => void openManageAccount()}>Get Stroke Pro <ExternalLink class="size-3.5 shrink-0" /></Button>
</div>
{:else if s.phase === 'setup'}
<div class="flex items-center justify-between gap-3">
<p class="text-ui-sm leading-relaxed text-muted-foreground">Keep workspaces, connections and settings in step on every device, end-to-end encrypted.</p>
Expand Down
9 changes: 9 additions & 0 deletions src/lib/stores/license.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,12 @@ export const hasPro = derived(
licenseStatus,
($s) => $s?.status !== 'TrialExpired',
)

/**
* Reactive: Pro that was paid for. The trial does not count: sync and
* scheduled backups need this (the server checks it too).
*/
export const hasPaidPro = derived(
licenseStatus,
($s) => $s?.status === 'Valid',
)
4 changes: 2 additions & 2 deletions src/lib/stores/scheduled-backups.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { invoke } from '@tauri-apps/api/core'
import { writable, get } from 'svelte/store'
import { Cron } from 'croner'
import { loadSavedConnections } from './connections.js'
import { hasPro } from './license.js'
import { hasPaidPro } from './license.js'
import { isSignedIn } from './account.js'

/**
Expand Down Expand Up @@ -150,7 +150,7 @@ let busy = false
let lastRefresh = 0

async function tick() {
if (busy || !get(isSignedIn) || !get(hasPro)) return
if (busy || !get(isSignedIn) || !get(hasPaidPro)) return
busy = true
try {
if (Date.now() - lastRefresh > REFRESH_MS || !get(backupOverview)) {
Expand Down
1 change: 1 addition & 0 deletions src/lib/sync/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export function pickSyncedSettings(s) {
export function syncLabel(s, now = Date.now()) {
switch (s.phase) {
case 'signed-out': return 'Sync off'
case 'pro': return 'Sync needs Pro'
case 'checking': return 'Checking sync…'
case 'setup': return 'Sync not set up'
case 'locked': return 'Sync locked'
Expand Down
43 changes: 38 additions & 5 deletions src/lib/sync/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { invoke } from '@tauri-apps/api/core'
import { writable, get } from 'svelte/store'
import { account } from '$lib/stores/account.js'
import { hasPaidPro, licenseStatus } from '$lib/stores/license.js'
import { workspaces, replaceWorkspaces, DEFAULT_WORKSPACE_ID } from '$lib/stores/workspaces.js'
import { loadSavedConnections, upsertConnection, removeConnection, newConnectionId } from '$lib/stores/connections.js'
import { loadSettings, updateSettings } from '$lib/stores/settings.js'
Expand Down Expand Up @@ -148,7 +149,7 @@ const engine = createSyncEngine({
// ── Status ────────────────────────────────────────────────────────────────────

/**
* @typedef {'signed-out' | 'checking' | 'setup' | 'locked' | 'ready' | 'syncing' | 'offline' | 'error'} SyncPhase
* @typedef {'signed-out' | 'checking' | 'pro' | 'setup' | 'locked' | 'ready' | 'syncing' | 'offline' | 'error'} SyncPhase
* @typedef {{ phase: SyncPhase, lastSyncedAt: number, items: number, error: string | null,
* keyChanged: boolean, undecryptable: number }} SyncStatus
*/
Expand Down Expand Up @@ -184,14 +185,20 @@ export async function refreshSyncState() {
setStatus({ phase: 'signed-out', error: null })
return get(syncStatus)
}
if (get(syncStatus).phase === 'signed-out') setStatus({ phase: 'checking' })
// Sync is part of paid Pro, not the trial: no server call to find that out.
if (!get(hasPaidPro)) {
setStatus({ phase: 'pro', error: null })
return get(syncStatus)
}
if (get(syncStatus).phase === 'signed-out' || get(syncStatus).phase === 'pro') setStatus({ phase: 'checking' })
try {
/** @type {{ signed_in: boolean, unlocked: boolean, server_has_key: boolean | null, key_changed: boolean, offline: boolean, error: string | null }} */
/** @type {{ signed_in: boolean, unlocked: boolean, server_has_key: boolean | null, key_changed: boolean, pro_required?: boolean, offline: boolean, error: string | null }} */
const st = await invoke('sync_state')
if (st.key_changed) resetSyncBookkeeping(localStorage)
/** @type {SyncPhase} */
let phase
if (!st.signed_in) phase = 'signed-out'
else if (st.pro_required) phase = 'pro'
else if (st.unlocked) phase = st.offline ? 'offline' : 'ready'
else if (st.server_has_key === false) phase = 'setup'
else if (st.server_has_key === true) phase = 'locked'
Expand Down Expand Up @@ -289,6 +296,10 @@ async function runOnce() {
setStatus({ keyChanged: true })
return
}
if (msg === 'pro_required') {
setStatus({ phase: 'pro', error: null })
return
}
if (msg === 'rate_limited') {
backoffUntil = Date.now() + BACKOFF_MS
setStatus({ phase: 'ready', error: 'The server asked Stroke to slow down. Sync resumes in a minute.' })
Expand Down Expand Up @@ -365,15 +376,37 @@ export function startSync() {
})
} catch { /* no window */ }

// Launch, sign-in and sign-out all arrive through the account store.
// Buying Pro (or losing it) changes what sync can do: ask again.
let wasPaid = /** @type {boolean | null} */ (null)
licenseStatus.subscribe(() => {
const paid = get(hasPaidPro)
if (paid === wasPaid) return
const first = wasPaid === null
wasPaid = paid
if (!first && get(account)?.signed_in) void refreshSyncState().then((st) => { if (st.phase === 'ready') void syncNow() })
})

// Launch, sign-in, sign-out and a switch to another account all arrive
// through the account store. Who is signed in matters, not only whether:
// signing in as someone else must not keep the last account's sync state.
let wasSignedIn = /** @type {boolean | null} */ (null)
let wasUser = /** @type {string | null} */ (null)
account.subscribe((a) => {
if (!a) return
const signedIn = !!a.signed_in
if (signedIn === wasSignedIn) return
const user = signedIn ? (a.user?.id ?? a.user?.email ?? '') : null
if (signedIn === wasSignedIn && user === wasUser) return
const before = wasSignedIn
const switched = !!before && signedIn && wasUser !== null && user !== wasUser
wasSignedIn = signedIn
wasUser = user
if (signedIn) {
if (switched) {
clearSyncBookkeeping(localStorage)
try { localStorage.removeItem(LAST_KEY) } catch { /* ignore */ }
}
// Start from nothing known: the phase is the new account's, not the last one's.
setStatus({ phase: 'checking', error: null, keyChanged: false, lastSyncedAt: switched ? 0 : get(syncStatus).lastSyncedAt, items: switched ? 0 : get(syncStatus).items })
lastFocus = Date.now()
void syncNow()
} else {
Expand Down
Loading