zad-cli 0.8.2

Command-line interface for zad — connects AI agents to external services (Discord, Slack, Google Calendar, Spotify, Telegram, YouTube Music, 1Password) via scoped service configurations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Spotify's plug-in to the generic service lifecycle.
//!
//! Everything Spotify-specific lives here: the OAuth 2.0 PKCE
//! credential shape (a public client — no `client_secret`), the flags
//! that let the operator paste in a pre-minted refresh token (or run
//! the interactive loopback flow), and the `GET /me` call that
//! validates a credential set. The generic plumbing (flag parsing,
//! path resolution, JSON envelopes, human banners, keychain I/O
//! sequencing) lives in `src/cli/lifecycle.rs` and is shared with
//! every other service.
//!
//! See `docs/services.md#adding-a-new-service` for the full recipe.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::cli::DialoguerExt;
use async_trait::async_trait;
use clap::Args;
use dialoguer::{Confirm, Input, theme::ColorfulTheme};

use crate::cli::lifecycle::{
    CliLifecycle, CreateArgsBase, CreateArgsLike, LifecycleService, ScopesArg, SecretRef,
    resolve_scopes,
};
use zad::config::{ProjectConfig, SpotifyServiceCfg};
use zad::error::{Result, ZadError};
use zad::oauth::{LoopbackConfig, RedirectScheme, RefreshTokenStore, run_loopback_flow};
use zad::secrets::{self, Scope};
use zad::service::spotify::{AUTH_URL, SpotifyHttp, TOKEN_URL, spotify_scopes_for};

const DEFAULT_SCOPES: &[&str] = &[
    "search",
    "playlists.read",
    "playlists.write",
    "library.read",
];
const ALL_SCOPES: &[&str] = &[
    "search",
    "playlists.read",
    "playlists.write",
    "library.read",
    "library.write",
];

/// URL the operator should visit to create a Spotify Developer app.
const SPOTIFY_DASHBOARD_URL: &str = "https://developer.spotify.com/dashboard";

/// Loopback callback deadline. Matches the default on
/// [`LoopbackConfig`] but spelled out here so the create flow can
/// print it to the user up front.
const LOOPBACK_TIMEOUT: Duration = Duration::from_secs(120);

// ---------------------------------------------------------------------------
// credential shape
// ---------------------------------------------------------------------------

/// Spotify's credential shape — OAuth 2.0 "Authorization Code with
/// PKCE" public client: just `client_id` + a long-lived `refresh_token`.
/// No client secret is issued or accepted by Spotify for PKCE clients.
/// Both pieces are persisted in the OS keychain; the access token is
/// re-minted at each CLI invocation.
pub struct SpotifySecrets {
    pub client_id: String,
    pub refresh_token: String,
}

// ---------------------------------------------------------------------------
// `zad service create spotify` args
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct CreateArgs {
    #[command(flatten)]
    pub base: CreateArgsBase,
    #[command(flatten)]
    pub scopes: ScopesArg,

    /// OAuth 2.0 client ID from the Spotify Developer Dashboard. Not
    /// strictly secret, but zad still stores it in the keychain for
    /// co-location with the refresh token.
    #[arg(long)]
    pub client_id: Option<String>,

    /// Read `--client-id` from this environment variable instead.
    #[arg(long, conflicts_with = "client_id")]
    pub client_id_env: Option<String>,

    /// Pre-minted OAuth refresh token. When provided, zad skips the
    /// browser loopback and stores the token verbatim. Useful for CI
    /// and for operators who already minted one out-of-band.
    #[arg(long, conflicts_with = "refresh_token_env")]
    pub refresh_token: Option<String>,

    /// Read `--refresh-token` from this environment variable instead.
    #[arg(long, conflicts_with = "refresh_token")]
    pub refresh_token_env: Option<String>,

    /// Optional default playlist for verbs that omit `--playlist`.
    /// Accepts a Spotify playlist ID, a `spotify:playlist:<id>` URI,
    /// or a directory alias.
    #[arg(long)]
    pub default_playlist: Option<String>,
}

impl CreateArgsLike for CreateArgs {
    fn base(&self) -> &CreateArgsBase {
        &self.base
    }
}

// ---------------------------------------------------------------------------
// the trait impl — the entire spotify-specific lifecycle surface
// ---------------------------------------------------------------------------

pub struct SpotifyLifecycle;

#[async_trait]
impl LifecycleService for SpotifyLifecycle {
    const NAME: &'static str = "spotify";
    const DISPLAY: &'static str = "Spotify";
    type Cfg = SpotifyServiceCfg;
    type Secrets = SpotifySecrets;

    fn enable_in_project(cfg: &mut ProjectConfig) {
        cfg.enable_spotify();
    }

    fn disable_in_project(cfg: &mut ProjectConfig) {
        cfg.disable_spotify();
    }

    async fn validate(_cfg: &SpotifyServiceCfg, creds: &mut SpotifySecrets) -> Result<String> {
        // Spotify's PKCE flow rotates the refresh token on every
        // `/api/token` call. The validate ping forces exactly such a
        // call, so we wire a tiny capture store that funnels any
        // rotation back into `creds.refresh_token` — the lifecycle
        // driver then writes the rotated value to the keychain via
        // `store_secrets`. Without this, the user would land in the
        // exact bug spotifai reported: keychain holds the
        // pre-rotation token, Spotify revokes it after the grace
        // window, the next runtime call fails with `invalid_grant`.
        let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
        let store = Arc::new(CaptureRefreshToken(captured.clone()));
        let http = SpotifyHttp::with_store(
            creds.client_id.clone(),
            creds.refresh_token.clone(),
            std::collections::BTreeSet::new(),
            std::path::PathBuf::new(),
            Some(store),
        );
        let me = http.me().await?;
        if let Some(rotated) = captured.lock().unwrap().take() {
            creds.refresh_token = rotated;
        }
        Ok(me.display_name.unwrap_or(me.id))
    }

    fn store_secrets(creds: &SpotifySecrets, scope: Scope<'_>) -> Result<Vec<SecretRef>> {
        let client_id_acct = secrets::account(Self::NAME, "client-id", scope.clone());
        let refresh_acct = secrets::account(Self::NAME, "refresh", scope);
        secrets::store(&client_id_acct, &creds.client_id)?;
        secrets::store(&refresh_acct, &creds.refresh_token)?;
        Ok(vec![
            SecretRef {
                label: "client id",
                account: client_id_acct,
                present: true,
            },
            SecretRef {
                label: "refresh token",
                account: refresh_acct,
                present: true,
            },
        ])
    }

    fn delete_secrets(scope: Scope<'_>) -> Result<Vec<SecretRef>> {
        let client_id_acct = secrets::account(Self::NAME, "client-id", scope.clone());
        let refresh_acct = secrets::account(Self::NAME, "refresh", scope);
        secrets::delete(&client_id_acct)?;
        secrets::delete(&refresh_acct)?;
        Ok(vec![
            SecretRef {
                label: "client id",
                account: client_id_acct,
                present: false,
            },
            SecretRef {
                label: "refresh token",
                account: refresh_acct,
                present: false,
            },
        ])
    }

    fn inspect_secrets(scope: Scope<'_>) -> Result<Vec<SecretRef>> {
        let client_id_acct = secrets::account(Self::NAME, "client-id", scope.clone());
        let refresh_acct = secrets::account(Self::NAME, "refresh", scope);
        let client_id_present = secrets::load(&client_id_acct)?.is_some();
        let refresh_present = secrets::load(&refresh_acct)?.is_some();
        Ok(vec![
            SecretRef {
                label: "client id",
                account: client_id_acct,
                present: client_id_present,
            },
            SecretRef {
                label: "refresh token",
                account: refresh_acct,
                present: refresh_present,
            },
        ])
    }

    fn load_secrets(scope: Scope<'_>) -> Result<Option<SpotifySecrets>> {
        let client_id_acct = secrets::account(Self::NAME, "client-id", scope.clone());
        let refresh_acct = secrets::account(Self::NAME, "refresh", scope);
        let (Some(id), Some(refresh)) = (
            secrets::load(&client_id_acct)?,
            secrets::load(&refresh_acct)?,
        ) else {
            return Ok(None);
        };
        Ok(Some(SpotifySecrets {
            client_id: id,
            refresh_token: refresh,
        }))
    }

    fn cfg_human(cfg: &SpotifyServiceCfg) -> Vec<(&'static str, String)> {
        let mut out = vec![];
        if let Some(p) = &cfg.default_playlist {
            out.push(("playlist", p.clone()));
        }
        out
    }

    fn cfg_json(cfg: &SpotifyServiceCfg) -> serde_json::Value {
        serde_json::json!({
            "default_playlist": cfg.default_playlist,
        })
    }

    fn scopes_of(cfg: &SpotifyServiceCfg) -> &[String] {
        &cfg.scopes
    }

    fn post_create_hint(_cfg: &SpotifyServiceCfg) -> Option<String> {
        None
    }
}

#[async_trait]
impl CliLifecycle for SpotifyLifecycle {
    type CreateArgs = CreateArgs;

    async fn resolve(
        args: &CreateArgs,
        non_interactive: bool,
    ) -> Result<(SpotifyServiceCfg, SpotifySecrets)> {
        let open_browser = !args.base.no_browser;

        let scopes = resolve_scopes(
            args.scopes.scopes.as_deref(),
            DEFAULT_SCOPES,
            ALL_SCOPES,
            non_interactive,
        )?;

        let client_id = resolve_client_id(
            args.client_id.as_deref(),
            args.client_id_env.as_deref(),
            open_browser,
            non_interactive,
        )?;

        let refresh_token = if let Some(v) = args.refresh_token.clone() {
            v
        } else if let Some(env) = args.refresh_token_env.as_deref() {
            std::env::var(env).map_err(|_| ZadError::MissingEnv(env.to_string()))?
        } else {
            resolve_refresh_via_loopback(&client_id, &scopes, open_browser, non_interactive).await?
        };

        Ok((
            SpotifyServiceCfg {
                scopes,
                default_playlist: args.default_playlist.clone(),
            },
            SpotifySecrets {
                client_id,
                refresh_token,
            },
        ))
    }
}

// ---------------------------------------------------------------------------
// prompt helpers
// ---------------------------------------------------------------------------

fn theme() -> ColorfulTheme {
    ColorfulTheme::default()
}

fn resolve_client_id(
    flag: Option<&str>,
    env_flag: Option<&str>,
    open_browser: bool,
    non_interactive: bool,
) -> Result<String> {
    if let Some(env) = env_flag {
        return std::env::var(env).map_err(|_| ZadError::MissingEnv(env.to_string()));
    }
    if let Some(v) = flag {
        return Ok(v.to_string());
    }
    if non_interactive {
        return Err(ZadError::MissingRequired("--client-id or --client-id-env"));
    }

    println!();
    println!("Spotify uses OAuth 2.0 (PKCE public client). You need a Spotify app:");
    println!("  1. Open the Spotify Developer Dashboard:");
    println!("       {SPOTIFY_DASHBOARD_URL}");
    println!("  2. Click \"Create app\". Name and description are arbitrary.");
    println!("  3. Under \"Redirect URIs\", add `https://127.0.0.1` and save.");
    println!("     (Spotify dropped HTTP for OAuth redirects — zad terminates TLS on the loopback");
    println!("     listener with a per-session self-signed cert; your browser will show a");
    println!(
        "     \"connection not private\" warning the first time you authorize — click through it.)"
    );
    println!("  4. Copy the Client ID from the app's Settings page back here.");
    println!("     (Spotify also shows a Client Secret — you do NOT need it for PKCE.)");
    if open_browser {
        let _ = open::that(SPOTIFY_DASHBOARD_URL);
    }

    let v: String = Input::with_theme(&theme())
        .with_prompt("Spotify Client ID")
        .interact_text()
        .into_zad()?;
    Ok(v.trim().to_string())
}

/// Interactive browser-based loopback flow for the refresh token.
/// Called only when the user didn't pass `--refresh-token` /
/// `--refresh-token-env`. Bails in non-interactive mode.
async fn resolve_refresh_via_loopback(
    client_id: &str,
    zad_scopes: &[String],
    open_browser: bool,
    non_interactive: bool,
) -> Result<String> {
    if non_interactive {
        return Err(ZadError::MissingRequired(
            "--refresh-token or --refresh-token-env (non-interactive mode cannot open a browser)",
        ));
    }

    println!();
    println!("No refresh token provided — starting the browser OAuth flow.");
    println!(
        "Make sure your Spotify app's \"Redirect URIs\" list includes `https://127.0.0.1` \
         (Spotify no longer accepts http://; the loopback listener picks a random port and \
         Spotify accepts any port on 127.0.0.1 once the host is registered). zad terminates \
         TLS on the loopback with a per-session self-signed cert, so your browser will show a \
         \"connection not private\" warning — click through it to finish authorization."
    );
    let want = Confirm::with_theme(&theme())
        .with_prompt("Continue with the browser flow?")
        .default(true)
        .interact()
        .into_zad()?;
    if !want {
        return Err(ZadError::Invalid(
            "browser OAuth flow declined by operator; pass --refresh-token to skip it".into(),
        ));
    }

    let provider_scopes = spotify_scopes_for(zad_scopes);
    let cfg = LoopbackConfig {
        service_name: "spotify",
        display_name: "Spotify",
        auth_url: AUTH_URL.to_string(),
        token_url: TOKEN_URL.to_string(),
        client_id: client_id.to_string(),
        client_secret: None,
        scopes: provider_scopes,
        // `show_dialog=true` forces Spotify to re-prompt for consent
        // even if the user previously authorized this app — without
        // it, a second `create` run silently re-uses the existing
        // grant and we never see a refresh token.
        extra_auth_params: vec![("show_dialog".into(), "true".into())],
        timeout: LOOPBACK_TIMEOUT,
        // Spotify deprecated `http://` redirect URIs (loopback
        // included). zad terminates TLS in-process with a self-signed
        // cert; the browser shows a one-time warning the operator
        // clicks through.
        redirect_scheme: RedirectScheme::Https,
    };
    let tokens = run_loopback_flow(&cfg, open_browser).await?;
    tokens.refresh_token.ok_or_else(|| ZadError::Service {
        name: "spotify",
        message: "Spotify did not return a refresh token. Re-run \
                  `zad service create spotify` to retry the consent flow."
            .into(),
    })
}

/// `RefreshTokenStore` impl that captures a rotated refresh token
/// into a shared cell instead of writing it anywhere. Used by
/// `SpotifyLifecycle::validate` so the lifecycle driver can take the
/// rotated value and persist it via `store_secrets` rather than
/// hard-coding a keychain write inside validate (the keychain slot
/// isn't yet authoritative at create time — `store_secrets` is the
/// single writer).
struct CaptureRefreshToken(Arc<Mutex<Option<String>>>);

impl RefreshTokenStore for CaptureRefreshToken {
    fn store(&self, refresh_token: &str) -> Result<()> {
        *self.0.lock().unwrap() = Some(refresh_token.to_string());
        Ok(())
    }
}