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` endpoint must not accept a
20// caller-supplied `user_id` — doing so allows arbitrary admin-JWT issuance
21// against any known user UUID on a public route. The CLI is colocated with
22// the database and holds the JWT signing secret, so it mints session rows
23// (and the JWTs above) locally instead of round-tripping through the public
24// HTTP endpoint. It goes through `SessionCreationService` rather than the
25// repository so every `user_sessions` row in the deployment is written by one
26// code path, whatever minted it.
27pub async fn create_local_session_row(
28    db_pool: &DbPool,
29    user: &UserId,
30    ttl: Duration,
31) -> Result<SessionId> {
32    let repositories = AnalyticsRepositories::new(db_pool)
33        .context("Failed to construct analytics repositories")?;
34    let analytics: Arc<dyn AnalyticsProvider> =
35        Arc::new(AnalyticsService::new(None, None, &repositories));
36    let user_repository =
37        Arc::new(UserRepository::new(db_pool).context("Failed to construct user repository")?);
38    let users: Arc<dyn UserProvider> = Arc::new(UserService::new(user_repository));
39
40    SessionCreationService::new(analytics, users)
41        .create_authenticated_session_with_ttl(
42            user,
43            &SessionAnalytics::default(),
44            SessionSource::Cli,
45            ttl,
46        )
47        .await
48        .context("Failed to insert CLI session row")
49}