1use crate::Cents;
2use crate::db::{billing_subscription, user};
3use crate::llm::{DEFAULT_MAX_MONTHLY_SPEND, FREE_TIER_MONTHLY_SPENDING_LIMIT};
4use crate::{Config, db::billing_preference};
5use anyhow::{Result, anyhow};
6use chrono::{NaiveDateTime, Utc};
7use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation};
8use serde::{Deserialize, Serialize};
9use std::time::Duration;
10use thiserror::Error;
11use util::maybe;
12use uuid::Uuid;
13use zed_llm_client::Plan;
14
15#[derive(Clone, Debug, Default, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub struct LlmTokenClaims {
18 pub iat: u64,
19 pub exp: u64,
20 pub jti: String,
21 pub user_id: u64,
22 pub system_id: Option<String>,
23 pub metrics_id: Uuid,
24 pub github_user_login: String,
25 pub account_created_at: NaiveDateTime,
26 pub is_staff: bool,
27 pub has_llm_closed_beta_feature_flag: bool,
28 pub bypass_account_age_check: bool,
29 pub has_llm_subscription: bool,
30 pub max_monthly_spend_in_cents: u32,
31 pub custom_llm_monthly_allowance_in_cents: Option<u32>,
32 pub plan: Plan,
33 #[serde(default)]
34 pub subscription_period: Option<(NaiveDateTime, NaiveDateTime)>,
35}
36
37const LLM_TOKEN_LIFETIME: Duration = Duration::from_secs(60 * 60);
38
39impl LlmTokenClaims {
40 pub fn create(
41 user: &user::Model,
42 is_staff: bool,
43 billing_preferences: Option<billing_preference::Model>,
44 feature_flags: &Vec<String>,
45 has_legacy_llm_subscription: bool,
46 plan: rpc::proto::Plan,
47 subscription: Option<billing_subscription::Model>,
48 system_id: Option<String>,
49 config: &Config,
50 ) -> Result<String> {
51 let secret = config
52 .llm_api_secret
53 .as_ref()
54 .ok_or_else(|| anyhow!("no LLM API secret"))?;
55
56 let now = Utc::now();
57 let claims = Self {
58 iat: now.timestamp() as u64,
59 exp: (now + LLM_TOKEN_LIFETIME).timestamp() as u64,
60 jti: uuid::Uuid::new_v4().to_string(),
61 user_id: user.id.to_proto(),
62 system_id,
63 metrics_id: user.metrics_id,
64 github_user_login: user.github_login.clone(),
65 account_created_at: user.account_created_at(),
66 is_staff,
67 has_llm_closed_beta_feature_flag: feature_flags
68 .iter()
69 .any(|flag| flag == "llm-closed-beta"),
70 bypass_account_age_check: feature_flags
71 .iter()
72 .any(|flag| flag == "bypass-account-age-check"),
73 has_llm_subscription: has_legacy_llm_subscription,
74 max_monthly_spend_in_cents: billing_preferences
75 .map_or(DEFAULT_MAX_MONTHLY_SPEND.0, |preferences| {
76 preferences.max_monthly_llm_usage_spending_in_cents as u32
77 }),
78 custom_llm_monthly_allowance_in_cents: user
79 .custom_llm_monthly_allowance_in_cents
80 .map(|allowance| allowance as u32),
81 plan: match plan {
82 rpc::proto::Plan::Free => Plan::Free,
83 rpc::proto::Plan::ZedPro => Plan::ZedPro,
84 rpc::proto::Plan::ZedProTrial => Plan::ZedProTrial,
85 },
86 subscription_period: maybe!({
87 let subscription = subscription?;
88 let period_start_at = subscription.current_period_start_at()?;
89 let period_end_at = subscription.current_period_end_at()?;
90
91 Some((period_start_at.naive_utc(), period_end_at.naive_utc()))
92 }),
93 };
94
95 Ok(jsonwebtoken::encode(
96 &Header::default(),
97 &claims,
98 &EncodingKey::from_secret(secret.as_ref()),
99 )?)
100 }
101
102 pub fn validate(token: &str, config: &Config) -> Result<LlmTokenClaims, ValidateLlmTokenError> {
103 let secret = config
104 .llm_api_secret
105 .as_ref()
106 .ok_or_else(|| anyhow!("no LLM API secret"))?;
107
108 match jsonwebtoken::decode::<Self>(
109 token,
110 &DecodingKey::from_secret(secret.as_ref()),
111 &Validation::default(),
112 ) {
113 Ok(token) => Ok(token.claims),
114 Err(e) => {
115 if e.kind() == &jsonwebtoken::errors::ErrorKind::ExpiredSignature {
116 Err(ValidateLlmTokenError::Expired)
117 } else {
118 Err(ValidateLlmTokenError::JwtError(e))
119 }
120 }
121 }
122 }
123
124 pub fn free_tier_monthly_spending_limit(&self) -> Cents {
125 self.custom_llm_monthly_allowance_in_cents
126 .map(Cents)
127 .unwrap_or(FREE_TIER_MONTHLY_SPENDING_LIMIT)
128 }
129}
130
131#[derive(Error, Debug)]
132pub enum ValidateLlmTokenError {
133 #[error("access token is expired")]
134 Expired,
135 #[error("access token validation error: {0}")]
136 JwtError(#[from] jsonwebtoken::errors::Error),
137 #[error("{0}")]
138 Other(#[from] anyhow::Error),
139}