Skip to main content

max / makenotwork

20.4 KB · 561 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)
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)?;
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 };
217 let result = match stripe.create_guest_checkout_session(&checkout_params).await {
218 Ok(r) => r,
219 Err(e) => {
220 release_promo().await;
221 return Err(e)
222 .with_context(|| format!("create guest Stripe checkout for item {item_id}"));
223 }
224 };
225
226 // Create pending transaction (buyer_id = None for guest). On a unique
227 // violation (a checkout for this item is already in progress) we must NOT
228 // return the live Stripe URL: there'd be no pending row for the webhook to
229 // complete, so the buyer would be charged and the sale silently lost.
230 // Release the promo and return an error (guests have no purchase page to
231 // redirect to, unlike the authenticated path).
232 match db::transactions::create_transaction(
233 &db,
234 &db::transactions::CreateTransactionParams {
235 buyer_id: None,
236 seller_id,
237 item_id: Some(item_id),
238 amount_cents: final_price_cents.into(),
239 platform_fee_cents: Cents::ZERO,
240 stripe_checkout_session_id: &result.id,
241 item_title: &item.title,
242 seller_username: &seller.username,
243 share_contact: false,
244 project_id: Some(item.project_id),
245 promo_code_id,
246 guest_email: None, // Set by webhook when Stripe provides it
247 platform_credit_cents: 0, // guests have no platform-wide credit (guarded above)
248 },
249 )
250 .await
251 {
252 Ok(_) => {}
253 // 23505 backstop. Note: the pending-checkout partial unique index is
254 // `(buyer_id, item_id) WHERE status = 'pending'`, and a guest row always
255 // has `buyer_id = NULL` (NULLS DISTINCT), so this branch does NOT dedup
256 // rapid guest re-submits the way it does for the authenticated path,
257 // guests have no stable identity at creation time (guest_email arrives
258 // later, from the Stripe webhook). Guest checkout flooding is instead
259 // bounded by the endpoint's per-IP rate limit (GUEST_CHECKOUT_RATE_LIMIT_*
260 // in api/mod.rs). This branch therefore only fires on the effectively
261 // impossible stripe_checkout_session_id collision; true per-guest dedup
262 // would need a client-supplied idempotency key (a protocol change).
263 Err(AppError::Database(sqlx::Error::Database(ref db_err)))
264 if db_err.code().as_deref() == Some("23505") =>
265 {
266 release_promo().await;
267 tracing::info!(item_id = %item_id, "duplicate pending guest checkout blocked");
268 return Err(AppError::BadRequest(
269 "A checkout for this item is already in progress. Please complete or cancel it before starting another.".to_string(),
270 ));
271 }
272 Err(e) => {
273 release_promo().await;
274 return Err(e).context("create pending guest transaction");
275 }
276 }
277
278 let checkout_url = result
279 .url
280 .ok_or_else(|| AppError::BadRequest("No checkout URL returned".to_string()))?;
281
282 let mut response = Json(CheckoutResponse { checkout_url }).into_response();
283
284 // CORS headers for cross-origin embed usage
285 let headers = response.headers_mut();
286 headers.insert(
287 header::ACCESS_CONTROL_ALLOW_ORIGIN,
288 HeaderValue::from_static("*"),
289 );
290 headers.insert(
291 header::ACCESS_CONTROL_ALLOW_METHODS,
292 HeaderValue::from_static("POST, OPTIONS"),
293 );
294 headers.insert(
295 header::ACCESS_CONTROL_ALLOW_HEADERS,
296 HeaderValue::from_static("content-type"),
297 );
298
299 Ok(response)
300 }
301
302 /// OPTIONS /api/checkout/guest/{item_id}: CORS preflight
303 pub(super) async fn guest_checkout_preflight() -> Response {
304 let mut response = StatusCode::NO_CONTENT.into_response();
305 let headers = response.headers_mut();
306 headers.insert(
307 header::ACCESS_CONTROL_ALLOW_ORIGIN,
308 HeaderValue::from_static("*"),
309 );
310 headers.insert(
311 header::ACCESS_CONTROL_ALLOW_METHODS,
312 HeaderValue::from_static("POST, OPTIONS"),
313 );
314 headers.insert(
315 header::ACCESS_CONTROL_ALLOW_HEADERS,
316 HeaderValue::from_static("content-type"),
317 );
318 headers.insert(
319 header::ACCESS_CONTROL_MAX_AGE,
320 HeaderValue::from_static("86400"),
321 );
322 response
323 }
324
325 /// GET /download/{download_token}
326 ///
327 /// Download a purchased item using a token from the guest purchase email.
328 /// No authentication required; the token is the proof of purchase.
329 #[tracing::instrument(skip_all, name = "guest_checkout::download")]
330 pub(super) async fn guest_download(
331 State(db): State<PgPool>,
332 State(storage): State<AppStorage>,
333 Path(token): Path<db::DownloadToken>,
334 ) -> Result<Response> {
335 let tx = db::transactions::get_transaction_by_download_token(&db, token)
336 .await?
337 .ok_or(AppError::NotFound)?;
338
339 let item_id = tx.item_id.ok_or(AppError::NotFound)?;
340 let item = db::items::get_item_by_id(&db, item_id)
341 .await?
342 .ok_or(AppError::NotFound)?;
343
344 // Resolve the downloadable file and the scan status that gates it. Items
345 // deliver either via an inline audio/video key or via a version file
346 // (software / digital-file items). A guest download token is item-scoped, so
347 // a version-delivered item resolves to its current file, the same file an
348 // authenticated buyer gets from the item page. Previously this path checked
349 // only the inline keys, so a guest who bought a version-delivered item got a
350 // token that 404'd despite having paid (Run 15 fulfillment gap).
351 let (s3_key, scan_status) = match item.audio_s3_key.clone().or(item.video_s3_key.clone()) {
352 Some(key) => (key, item.scan_status),
353 None => db::versions::get_versions_by_item(&db, item_id)
354 .await?
355 .into_iter()
356 .filter_map(|v| {
357 v.s3_key
358 .map(|k| (k, v.scan_status, v.is_current, v.created_at))
359 })
360 // Prefer the current version, then the most recent, matching what the
361 // item page hands an authenticated buyer.
362 .max_by(|a, b| a.2.cmp(&b.2).then(a.3.cmp(&b.3)))
363 .map(|(key, status, _, _)| (key, status))
364 .ok_or(AppError::NotFound)?,
365 };
366
367 // Gate on scan status, exactly as the authenticated download path does
368 // (downloads.rs). A guest is never the creator, so there is no preview
369 // exemption: only Clean content is downloadable, Pending/HeldForReview/
370 // Quarantined are withheld until the scan clears (Sec NOTE, Run 7; the guest
371 // path previously skipped this quarantine check entirely).
372 if scan_status != db::FileScanStatus::Clean {
373 return Err(AppError::NotFound);
374 }
375
376 let s3 = storage.s3.as_ref().ok_or_else(|| {
377 AppError::ServiceUnavailable("File storage is not configured".to_string())
378 })?;
379
380 let download_url = s3
381 .presign_download(&crate::storage::S3Key::from_stored(&s3_key), Some(3600))
382 .await?;
383
384 Ok(Redirect::temporary(&download_url).into_response())
385 }
386
387 /// POST /api/purchases/claim
388 ///
389 /// Attach a guest purchase to the authenticated user's account using a claim token.
390 #[tracing::instrument(skip_all, name = "guest_checkout::claim")]
391 pub(super) async fn claim_purchase(
392 State(db): State<PgPool>,
393 State(integrations): State<Integrations>,
394 crate::auth::AuthUser(user): crate::auth::AuthUser,
395 Json(body): Json<ClaimRequest>,
396 ) -> Result<Response> {
397 user.check_not_sandbox()?;
398 let tx = db::transactions::claim_guest_purchase(&db, body.claim_token, user.id)
399 .await?
400 .ok_or_else(|| AppError::BadRequest("Invalid or already-claimed token".to_string()))?;
401
402 tracing::info!(
403 user_id = %user.id,
404 transaction_id = %tx.id,
405 "guest purchase claimed"
406 );
407
408 // Issue the license key at claim time. Guest purchases of key-enabled items
409 // are no longer auto-attached on an email match (the buyer always claims via
410 // the emailed link), so the key must be minted here, the claim is the point
411 // at which a real, authenticated buyer is known. `claim_guest_purchase`'s
412 // `buyer_id IS NULL` guard makes the claim single-use, so this runs at most
413 // once per purchase.
414 if let Some(item_id) = tx.item_id {
415 crate::routes::stripe::webhook::checkout_helpers::maybe_generate_license_key(
416 &db,
417 integrations.wam.as_ref(),
418 item_id,
419 user.id,
420 tx.id,
421 )
422 .await;
423 }
424
425 Ok(StatusCode::OK.into_response())
426 }
427
428 #[derive(Debug, Deserialize)]
429 pub(super) struct ClaimRequest {
430 pub claim_token: db::ClaimToken,
431 }
432
433 /// Request body for free guest claim.
434 #[derive(Debug, Deserialize)]
435 pub(super) struct FreeGuestClaimRequest {
436 pub email: String,
437 }
438
439 /// POST /api/checkout/guest-free/{item_id}
440 ///
441 /// Claim a free item as a guest. Collects email, creates a completed transaction,
442 /// and sends download + claim links via email. No Stripe involved.
443 #[tracing::instrument(skip_all, name = "guest_checkout::claim_free")]
444 pub(super) async fn claim_free_guest(
445 State(db): State<PgPool>,
446 State(config): State<Config>,
447 State(email_client): State<EmailClient>,
448 State(bg): State<BackgroundTx>,
449 Path(item_id): Path<ItemId>,
450 Json(body): Json<FreeGuestClaimRequest>,
451 ) -> Result<Response> {
452 let email = db::Email::new(&body.email)
453 .map_err(|_| AppError::BadRequest("Invalid email address".to_string()))?;
454
455 let item = db::items::get_item_by_id(&db, item_id)
456 .await?
457 .ok_or(AppError::NotFound)?;
458
459 if !item.is_public || !item.listed || item.price_cents != 0 {
460 return Err(AppError::NotFound);
461 }
462
463 // Fetch seller
464 let project = db::projects::get_project_by_id(&db, item.project_id)
465 .await?
466 .ok_or(AppError::NotFound)?;
467 let seller = db::users::get_user_by_id(&db, project.user_id)
468 .await?
469 .ok_or(AppError::NotFound)?;
470
471 if seller.is_suspended() || seller.is_deactivated() || seller.is_creator_paused() {
472 return Err(AppError::NotFound);
473 }
474
475 // Never auto-attach on an email match, a typed address isn't proof the
476 // claimant controls it. The buyer always claims via the emailed link,
477 // consistent with the paid guest path (Run #21 / Max's call 2026-06-15).
478 let claim_token = db::ClaimToken::new();
479 let download_token = db::DownloadToken::new();
480 let checkout_session_id = format!("free-guest-{email}-{item_id}");
481
482 // Create completed transaction
483 let result = db::transactions::create_free_guest_transaction(
484 &db,
485 None,
486 seller.id,
487 item_id,
488 &checkout_session_id,
489 &item.title,
490 &seller.username,
491 email.as_str(),
492 Some(claim_token),
493 download_token,
494 )
495 .await;
496
497 match result {
498 Ok(0) => {
499 // Already claimed, still send the email with download link
500 }
501 Ok(_) => {
502 let _ = db::items::increment_sales_count(&db, item_id).await;
503 }
504 Err(e) => {
505 // Unique violation (already in library for existing user)
506 if let sqlx::Error::Database(ref db_err) = e {
507 if db_err.code().as_deref() == Some("23505") {
508 // Already claimed, continue to send email
509 } else {
510 return Err(AppError::Database(e));
511 }
512 } else {
513 return Err(AppError::Database(e));
514 }
515 }
516 }
517
518 // Send download email
519 let host_url = &config.host_url;
520 let download_url = format!("{host_url}/download/{download_token}");
521 let claim_url = format!("{host_url}/claim?token={claim_token}");
522
523 // Always send the claim link, there's no auto-attach to skip it for.
524 {
525 let email_client = email_client.clone();
526 let email_addr = email.clone().into_inner();
527 let item_title = item.title.clone();
528 let dl_url = download_url.clone();
529 let cl_url = claim_url;
530 bg.spawn("free guest claim email", async move {
531 if let Err(e) = email_client
532 .send_guest_purchase_confirmation(
533 &email_addr,
534 &item_title,
535 "Free",
536 &dl_url,
537 &cl_url,
538 )
539 .await
540 {
541 tracing::error!(error = ?e, "failed to send free guest claim email");
542 }
543 });
544 }
545
546 let mut response = Json(serde_json::json!({
547 "status": "claimed",
548 "download_url": download_url,
549 }))
550 .into_response();
551
552 // CORS headers
553 let headers = response.headers_mut();
554 headers.insert(
555 header::ACCESS_CONTROL_ALLOW_ORIGIN,
556 HeaderValue::from_static("*"),
557 );
558
559 Ok(response)
560 }
561