Skip to main content

systemprompt_cli/session/
api.rs

1//! Local session and JWT minting for CLI commands.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use anyhow::{Context, Result};
7use chrono::Duration;
8use std::sync::Arc;
9use systemprompt_analytics::AnalyticsService;
10use systemprompt_analytics::repository::AnalyticsRepositories;
11use systemprompt_database::DbPool;
12use systemprompt_identifiers::{SessionId, SessionSource, UserId};
13use systemprompt_oauth::services::SessionCreationService;
14use systemprompt_traits::{AnalyticsProvider, SessionAnalytics, UserProvider};
15use systemprompt_users::{UserRepository, UserService};
16
17pub const DEFAULT_CLI_SESSION_HOURS: i64 = 24;
18
19// Why: the public `POST /oauth/session` must not accept a caller-supplied
20// `user_id` — that would allow admin-JWT issuance against any known user UUID
21// on a public route. The CLI holds the signing secret and the database, so it
22// mints session rows locally, through `SessionCreationService` rather than
23// the repository so every `user_sessions` row is written by one code path.
24pub async fn create_local_session_row(
25    db_pool: &DbPool,
26    user: &UserId,
27    ttl: Duration,
28) -> Result<SessionId> {
29    let repositories = AnalyticsRepositories::new(db_pool)
30        .context("Failed to construct analytics repositories")?;
31    let analytics: Arc<dyn AnalyticsProvider> =
32        Arc::new(AnalyticsService::new(None, None, &repositories));
33    let user_repository =
34        Arc::new(UserRepository::new(db_pool).context("Failed to construct user repository")?);
35    let users: Arc<dyn UserProvider> = Arc::new(UserService::new(user_repository));
36
37    SessionCreationService::new(analytics, users)
38        .create_authenticated_session_with_ttl(
39            user,
40            &SessionAnalytics::default(),
41            SessionSource::Cli,
42            ttl,
43        )
44        .await
45        .context("Failed to insert CLI session row")
46}