Skip to main content

max / makenotwork

20.7 KB · 564 lines History Blame Raw
1 //! Guest checkout: purchase items without an MNW account.
2 //!
3 //! These endpoints are public (no auth required) and CORS-enabled for use from
4 //! embedded widgets on external sites.
5
6 use axum::{
7 Json,
8 extract::{Path, State},
9 http::{HeaderValue, StatusCode, header},
10 response::{IntoResponse, Redirect, Response},
11 };
12 use serde::{Deserialize, Serialize};
13
14 use crate::background::BackgroundTx;
15 use crate::config::Config;
16 use crate::email::EmailClient;
17 use crate::{AppStorage, Billing, Integrations};
18 use sqlx::PgPool;
19
20 use crate::{
21 db::{self, Cents, ItemId},
22 error::{AppError, Result, ResultExt},
23 };
24
25 /// Request body for creating a guest checkout session.
26 #[derive(Debug, Deserialize)]
27 pub(super) struct GuestCheckoutRequest {
28 /// Buyer-chosen amount in cents (only for PWYW items).
29 pub amount_cents: Option<i32>,
30 /// Optional promo/discount code.
31 pub promo_code: Option<String>,
32 }
33
34 /// Response from creating a guest checkout session.
35 #[derive(Serialize)]
36 struct CheckoutResponse {
37 checkout_url: String,
38 }
39
40 /// POST /api/checkout/guest/{item_id}
41 ///
42 /// Creates a Stripe Checkout Session for a guest purchase (no account required).
43 /// Returns the Stripe checkout URL. The embed or item page opens this in a popup
44 /// or redirects to it.
45 #[tracing::instrument(skip_all, name = "guest_checkout::create")]
46 pub(super) async fn create_guest_checkout(
47 State(db): State<PgPool>,
48 State(config): State<Config>,
49 State(payments): State<Billing>,
50 Path(item_id): Path<ItemId>,
51 Json(body): Json<GuestCheckoutRequest>,
52 ) -> Result<Response> {
53 // Fetch item
54 let item = db::items::get_item_by_id(&db, item_id)
55 .await?
56 .ok_or(AppError::NotFound)?;
57
58 if !item.is_public || !item.listed {
59 return Err(AppError::NotFound);
60 }
61
62 // Fetch seller via project
63 let project = db::projects::get_project_by_id(&db, item.project_id)
64 .await?
65 .ok_or(AppError::NotFound)?;
66 let seller = db::users::get_user_by_id(&db, project.user_id)
67 .await?
68 .ok_or(AppError::NotFound)?;
69
70 if seller.is_suspended() || seller.is_deactivated() || seller.is_creator_paused() {
71 return Err(AppError::NotFound);
72 }
73
74 let seller_id = seller.id;
75
76 // Determine price, use the same pricing model as the authenticated checkout
77 let pricing = crate::pricing::for_item(&item);
78 let mut final_price_cents = if item.pwyw_enabled {
79 let buyer_amount = body.amount_cents.unwrap_or(item.price_cents);
80 pricing
81 .validate_amount(buyer_amount, seller.settlement_currency)
82 .map_err(AppError::BadRequest)?;
83 buyer_amount
84 } else {
85 item.price_cents
86 };
87
88 // Free items: skip Stripe entirely, redirect to the free claim endpoint
89 if final_price_cents == 0 {
90 return Err(AppError::BadRequest(
91 "Free items use /api/checkout/guest-free/{item_id} instead".to_string(),
92 ));
93 }
94
95 // Resolve and validate promo code with the same checks as authenticated checkout
96 let mut promo_code_id = None;
97 if let Some(code_str) = body
98 .promo_code
99 .as_deref()
100 .map(str::trim)
101 .filter(|s| !s.is_empty())
102 {
103 if item.pwyw_enabled {
104 return Err(AppError::BadRequest(
105 "Promo codes cannot be applied to pay-what-you-want items".to_string(),
106 ));
107 }
108 // Guests have no account, so no platform-wide Fan+ credit fallback (None).
109 if let Some(validated) =
110 db::promo_codes::lookup_and_validate_promo(&db, seller_id, None, code_str).await?
111 {
112 use db::promo_codes::{PromoApplication, PromoIneligible};
113 match db::promo_codes::apply_promo_to_item(
114 &validated,
115 item_id,
116 item.project_id,
117 item.price_cents,
118 )? {
119 PromoApplication::Apply(applied) => {
120 // Guests have no account and thus no platform-wide Fan+ credit, so a
121 // guest discount is always creator-funded. Guard the invariant rather
122 // than silently dropping a reimbursement obligation.
123 if applied.funding.platform_credit_cents() > 0 {
124 return Err(AppError::BadRequest(
125 "This code cannot be used for guest checkout".to_string(),
126 ));
127 }
128 final_price_cents = applied.price_cents;
129 }
130 PromoApplication::Ineligible(PromoIneligible::ScopeMismatch) => {
131 return Err(AppError::BadRequest(
132 "This promo code is not valid for this item".to_string(),
133 ));
134 }
135 PromoApplication::Ineligible(PromoIneligible::BelowMinPrice) => {
136 return Err(AppError::BadRequest(
137 "This item does not meet the minimum price for this code".to_string(),
138 ));
139 }
140 }
141 promo_code_id = Some(validated.id());
142 }
143 }
144
145 // If a promo code brought the price to zero, redirect to the free claim flow
146 if final_price_cents == 0 {
147 return Err(AppError::BadRequest(
148 "Free items use /api/checkout/guest-free/{item_id} instead".to_string(),
149 ));
150 }
151
152 // Reject sub-Stripe-minimum charges (a Discount promo can land a fixed item
153 // at 1–49¢) using the shared `check_min_charge` the Stripe session call
154 // enforces internally. Gating here, before the promo reservation, means a
155 // rejection doesn't burn a use of the code.
156 crate::payments::check_min_charge(final_price_cents as i64, seller.settlement_currency)?;
157
158 // Verify seller has Stripe configured
159 let stripe_account_id = seller
160 .stripe_account_id
161 .as_deref()
162 .ok_or_else(|| AppError::BadRequest("Creator hasn't set up payments yet".to_string()))?;
163 if !seller.stripe_charges_enabled {
164 return Err(AppError::BadRequest(
165 "Creator's payment account is not ready".to_string(),
166 ));
167 }
168
169 let stripe = payments
170 .stripe
171 .as_ref()
172 .ok_or_else(|| AppError::BadRequest("Stripe is not configured".to_string()))?;
173
174 // Reserve the promo code BEFORE creating the Stripe session or pending row,
175 // mirroring the authenticated item-checkout path. The old order (reserve
176 // last) meant a swallowed 23505 returned a live checkout URL with NO pending
177 // row for the webhook to complete, the buyer paid and the sale vanished,
178 // and a failed reservation could orphan the pending row's promo. Every
179 // failure path below now releases this reservation.
180 if let Some(pc_id) = promo_code_id {
181 let reserved = db::promo_codes::try_increment_use_count(&db, pc_id)
182 .await
183 .context("reserve promo code use at guest checkout")?;
184 if !reserved {
185 return Err(AppError::BadRequest(
186 "This promo code has reached its usage limit".to_string(),
187 ));
188 }
189 }
190
191 // Release the reservation above on any failure path below (no-op if no promo).
192 let release_promo = || async {
193 if let Some(pc_id) = promo_code_id {
194 db::promo_codes::release_use_count(&db, pc_id).await.ok();
195 }
196 };
197
198 // Build URLs
199 let success_url = format!(
200 "{}/stripe/success?session_id={{CHECKOUT_SESSION_ID}}",
201 config.host_url
202 );
203 let cancel_url = format!("{}/i/{}", config.host_url, item_id);
204
205 // Create guest checkout session
206 let checkout_params = crate::payments::GuestCheckoutParams {
207 connected_account_id: stripe_account_id,
208 item_title: &item.title,
209 amount_cents: Cents::new(final_price_cents as i64),
210 seller_id,
211 item_id,
212 success_url: &success_url,
213 cancel_url: &cancel_url,
214 promo_code_id,
215 enable_stripe_tax: seller.stripe_tax_enabled,
216 currency: seller.settlement_currency,
217 // A guest has no stored preference, so they get the default: the path
218 // where Stripe shows the converted total before they commit.
219 conversion: crate::currency::ConversionChoice::default(),
220 };
221 let result = match stripe.create_guest_checkout_session(&checkout_params).await {
222 Ok(r) => r,
223 Err(e) => {
224 release_promo().await;
225 return Err(e)
226 .with_context(|| format!("create guest Stripe checkout for item {item_id}"));
227 }
228 };
229
230 // Create pending transaction (buyer_id = None for guest). If the insert
231 // fails we must NOT return the live Stripe URL: there'd be no pending row
232 // for the webhook to complete, so the buyer would be charged and the sale
233 // silently lost. Release the promo and return an error (guests have no
234 // purchase page to redirect to, unlike the authenticated path).
235 match db::transactions::create_transaction(
236 &db,
237 &db::transactions::CreateTransactionParams {
238 buyer_id: None,
239 seller_id,
240 item_id: Some(item_id),
241 amount_cents: final_price_cents.into(),
242 platform_fee_cents: Cents::ZERO,
243 stripe_checkout_session_id: &result.id,
244 item_title: &item.title,
245 seller_username: &seller.username,
246 share_contact: false,
247 project_id: Some(item.project_id),
248 promo_code_id,
249 guest_email: None, // Set by webhook when Stripe provides it
250 platform_credit_cents: 0, // guests have no platform-wide credit (guarded above)
251 },
252 )
253 .await
254 {
255 Ok(_) => {}
256 // 23505 backstop. Note: the pending-checkout partial unique index is
257 // `(buyer_id, item_id) WHERE status = 'pending'`, and a guest row always
258 // has `buyer_id = NULL` (NULLS DISTINCT), so this branch does NOT dedup
259 // rapid guest re-submits the way it does for the authenticated path,
260 // guests have no stable identity at creation time (guest_email arrives
261 // later, from the Stripe webhook). Guest checkout flooding is instead
262 // bounded by the endpoint's per-IP rate limit (GUEST_CHECKOUT_RATE_LIMIT_*
263 // in api/mod.rs). This branch therefore only fires on the effectively
264 // impossible stripe_checkout_session_id collision; true per-guest dedup
265 // would need a client-supplied idempotency key (a protocol change).
266 Err(AppError::Database(sqlx::Error::Database(ref db_err)))
267 if db_err.code().as_deref() == Some("23505") =>
268 {
269 release_promo().await;
270 tracing::info!(item_id = %item_id, "duplicate pending guest checkout blocked");
271 return Err(AppError::BadRequest(
272 "A checkout for this item is already in progress. Please complete or cancel it before starting another.".to_string(),
273 ));
274 }
275 Err(e) => {
276 release_promo().await;
277 return Err(e).context("create pending guest transaction");
278 }
279 }
280
281 let checkout_url = result
282 .url
283 .ok_or_else(|| AppError::BadRequest("No checkout URL returned".to_string()))?;
284
285 let mut response = Json(CheckoutResponse { checkout_url }).into_response();
286
287 // CORS headers for cross-origin embed usage
288 let headers = response.headers_mut();
289 headers.insert(
290 header::ACCESS_CONTROL_ALLOW_ORIGIN,
291 HeaderValue::from_static("*"),
292 );
293 headers.insert(
294 header::ACCESS_CONTROL_ALLOW_METHODS,
295 HeaderValue::from_static("POST, OPTIONS"),
296 );
297 headers.insert(
298 header::ACCESS_CONTROL_ALLOW_HEADERS,
299 HeaderValue::from_static("content-type"),
300 );
301
302 Ok(response)
303 }
304
305 /// OPTIONS /api/checkout/guest/{item_id}: CORS preflight
306 pub(super) async fn guest_checkout_preflight() -> Response {
307 let mut response = StatusCode::NO_CONTENT.into_response();
308 let headers = response.headers_mut();
309 headers.insert(
310 header::ACCESS_CONTROL_ALLOW_ORIGIN,
311 HeaderValue::from_static("*"),
312 );
313 headers.insert(
314 header::ACCESS_CONTROL_ALLOW_METHODS,
315 HeaderValue::from_static("POST, OPTIONS"),
316 );
317 headers.insert(
318 header::ACCESS_CONTROL_ALLOW_HEADERS,
319 HeaderValue::from_static("content-type"),
320 );
321 headers.insert(
322 header::ACCESS_CONTROL_MAX_AGE,
323 HeaderValue::from_static("86400"),
324 );
325 response
326 }
327
328 /// GET /download/{download_token}
329 ///
330 /// Download a purchased item using a token from the guest purchase email.
331 /// No authentication required; the token is the proof of purchase.
332 #[tracing::instrument(skip_all, name = "guest_checkout::download")]
333 pub(super) async fn guest_download(
334 State(db): State<PgPool>,
335 State(storage): State<AppStorage>,
336 Path(token): Path<db::DownloadToken>,
337 ) -> Result<Response> {
338 let tx = db::transactions::get_transaction_by_download_token(&db, token)
339 .await?
340 .ok_or(AppError::NotFound)?;
341
342 let item_id = tx.item_id.ok_or(AppError::NotFound)?;
343 let item = db::items::get_item_by_id(&db, item_id)
344 .await?
345 .ok_or(AppError::NotFound)?;
346
347 // Resolve the downloadable file and the scan status that gates it. Items
348 // deliver either via an inline audio/video key or via a version file
349 // (software / digital-file items). A guest download token is item-scoped, so
350 // a version-delivered item resolves to its current file, the same file an
351 // authenticated buyer gets from the item page. Previously this path checked
352 // only the inline keys, so a guest who bought a version-delivered item got a
353 // token that 404'd despite having paid (Run 15 fulfillment gap).
354 let (s3_key, scan_status) = match item.audio_s3_key.clone().or(item.video_s3_key.clone()) {
355 Some(key) => (key, item.scan_status),
356 None => db::versions::get_versions_by_item(&db, item_id)
357 .await?
358 .into_iter()
359 .filter_map(|v| {
360 v.s3_key
361 .map(|k| (k, v.scan_status, v.is_current, v.created_at))
362 })
363 // Prefer the current version, then the most recent, matching what the
364 // item page hands an authenticated buyer.
365 .max_by(|a, b| a.2.cmp(&b.2).then(a.3.cmp(&b.3)))
366 .map(|(key, status, _, _)| (key, status))
367 .ok_or(AppError::NotFound)?,
368 };
369
370 // Gate on scan status, exactly as the authenticated download path does
371 // (downloads.rs). A guest is never the creator, so there is no preview
372 // exemption: only Clean content is downloadable, Pending/HeldForReview/
373 // Quarantined are withheld until the scan clears (Sec NOTE, Run 7; the guest
374 // path previously skipped this quarantine check entirely).
375 if scan_status != db::FileScanStatus::Clean {
376 return Err(AppError::NotFound);
377 }
378
379 let s3 = storage.s3.as_ref().ok_or_else(|| {
380 AppError::ServiceUnavailable("File storage is not configured".to_string())
381 })?;
382
383 let download_url = s3
384 .presign_download(&crate::storage::S3Key::from_stored(&s3_key), Some(3600))
385 .await?;
386
387 Ok(Redirect::temporary(&download_url).into_response())
388 }
389
390 /// POST /api/purchases/claim
391 ///
392 /// Attach a guest purchase to the authenticated user's account using a claim token.
393 #[tracing::instrument(skip_all, name = "guest_checkout::claim")]
394 pub(super) async fn claim_purchase(
395 State(db): State<PgPool>,
396 State(integrations): State<Integrations>,
397 crate::auth::AuthUser(user): crate::auth::AuthUser,
398 Json(body): Json<ClaimRequest>,
399 ) -> Result<Response> {
400 user.check_not_sandbox()?;
401 let tx = db::transactions::claim_guest_purchase(&db, body.claim_token, user.id)
402 .await?
403 .ok_or_else(|| AppError::BadRequest("Invalid or already-claimed token".to_string()))?;
404
405 tracing::info!(
406 user_id = %user.id,
407 transaction_id = %tx.id,
408 "guest purchase claimed"
409 );
410
411 // Issue the license key at claim time. Guest purchases of key-enabled items
412 // are no longer auto-attached on an email match (the buyer always claims via
413 // the emailed link), so the key must be minted here, the claim is the point
414 // at which a real, authenticated buyer is known. `claim_guest_purchase`'s
415 // `buyer_id IS NULL` guard makes the claim single-use, so this runs at most
416 // once per purchase.
417 if let Some(item_id) = tx.item_id {
418 crate::routes::stripe::webhook::checkout_helpers::maybe_generate_license_key(
419 &db,
420 integrations.wam.as_ref(),
421 item_id,
422 user.id,
423 tx.id,
424 )
425 .await;
426 }
427
428 Ok(StatusCode::OK.into_response())
429 }
430
431 #[derive(Debug, Deserialize)]
432 pub(super) struct ClaimRequest {
433 pub claim_token: db::ClaimToken,
434 }
435
436 /// Request body for free guest claim.
437 #[derive(Debug, Deserialize)]
438 pub(super) struct FreeGuestClaimRequest {
439 pub email: String,
440 }
441
442 /// POST /api/checkout/guest-free/{item_id}
443 ///
444 /// Claim a free item as a guest. Collects email, creates a completed transaction,
445 /// and sends download + claim links via email. No Stripe involved.
446 #[tracing::instrument(skip_all, name = "guest_checkout::claim_free")]
447 pub(super) async fn claim_free_guest(
448 State(db): State<PgPool>,
449 State(config): State<Config>,
450 State(email_client): State<EmailClient>,
451 State(bg): State<BackgroundTx>,
452 Path(item_id): Path<ItemId>,
453 Json(body): Json<FreeGuestClaimRequest>,
454 ) -> Result<Response> {
455 let email = db::Email::new(&body.email)
456 .map_err(|_| AppError::BadRequest("Invalid email address".to_string()))?;
457
458 let item = db::items::get_item_by_id(&db, item_id)
459 .await?
460 .ok_or(AppError::NotFound)?;
461
462 if !item.is_public || !item.listed || item.price_cents != 0 {
463 return Err(AppError::NotFound);
464 }
465
466 // Fetch seller
467 let project = db::projects::get_project_by_id(&db, item.project_id)
468 .await?
469 .ok_or(AppError::NotFound)?;
470 let seller = db::users::get_user_by_id(&db, project.user_id)
471 .await?
472 .ok_or(AppError::NotFound)?;
473
474 if seller.is_suspended() || seller.is_deactivated() || seller.is_creator_paused() {
475 return Err(AppError::NotFound);
476 }
477
478 // Never auto-attach on an email match, a typed address isn't proof the
479 // claimant controls it. The buyer always claims via the emailed link,
480 // consistent with the paid guest path (Run #21 / Max's call 2026-06-15).
481 let claim_token = db::ClaimToken::new();
482 let download_token = db::DownloadToken::new();
483 let checkout_session_id = format!("free-guest-{email}-{item_id}");
484
485 // Create completed transaction
486 let result = db::transactions::create_free_guest_transaction(
487 &db,
488 None,
489 seller.id,
490 item_id,
491 &checkout_session_id,
492 &item.title,
493 &seller.username,
494 email.as_str(),
495 Some(claim_token),
496 download_token,
497 )
498 .await;
499
500 match result {
501 Ok(0) => {
502 // Already claimed, still send the email with download link
503 }
504 Ok(_) => {
505 let _ = db::items::increment_sales_count(&db, item_id).await;
506 }
507 Err(e) => {
508 // Unique violation (already in library for existing user)
509 if let sqlx::Error::Database(ref db_err) = e {
510 if db_err.code().as_deref() == Some("23505") {
511 // Already claimed, continue to send email
512 } else {
513 return Err(AppError::Database(e));
514 }
515 } else {
516 return Err(AppError::Database(e));
517 }
518 }
519 }
520
521 // Send download email
522 let host_url = &config.host_url;
523 let download_url = format!("{host_url}/download/{download_token}");
524 let claim_url = format!("{host_url}/claim?token={claim_token}");
525
526 // Always send the claim link, there's no auto-attach to skip it for.
527 {
528 let email_client = email_client.clone();
529 let email_addr = email.clone().into_inner();
530 let item_title = item.title.clone();
531 let dl_url = download_url.clone();
532 let cl_url = claim_url;
533 bg.spawn("free guest claim email", async move {
534 if let Err(e) = email_client
535 .send_guest_purchase_confirmation(
536 &email_addr,
537 &item_title,
538 "Free",
539 &dl_url,
540 &cl_url,
541 )
542 .await
543 {
544 tracing::error!(error = ?e, "failed to send free guest claim email");
545 }
546 });
547 }
548
549 let mut response = Json(serde_json::json!({
550 "status": "claimed",
551 "download_url": download_url,
552 }))
553 .into_response();
554
555 // CORS headers
556 let headers = response.headers_mut();
557 headers.insert(
558 header::ACCESS_CONTROL_ALLOW_ORIGIN,
559 HeaderValue::from_static("*"),
560 );
561
562 Ok(response)
563 }
564