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