Skip to main content

max / makenotwork

31.7 KB · 848 lines History Blame Raw
1 //! JSON API endpoints for projects, items, links, and tags.
2 //!
3 //! ## Response conventions
4 //!
5 //! - **Create / Update**: return the full resource as JSON.
6 //! - **Delete**: return `204 No Content`.
7 //! - **List**: return `{"data": [...]}` via [`ListResponse`](crate::types::ListResponse).
8 //! - **Action** (no resource to return): `204` or `{"message": "..."}`.
9 //! - **Errors**: `{"error": "..."}` with appropriate HTTP status (via [`json_error_layer`]).
10 //! - **HTMX**: response pattern varies by UX need (toast, redirect, partial,
11 //! save-status); intentional, not inconsistency.
12 //! - **License key public endpoints** (`/api/keys/*`): stable API contract,
13 //! response shapes are frozen.
14 //!
15 //! List endpoints on the creator dashboard (tiers, keys, codes, chapters, etc.)
16 //! are intentionally unpaginated; each is scoped to a single project or user,
17 //! producing bounded result sets (typically <100 items).
18
19 mod blog;
20 mod cart;
21 mod categories;
22 mod collections;
23 mod content_insertions;
24 mod csp_report;
25 mod domains;
26 mod exports;
27 mod follows;
28 pub(crate) mod git_notes;
29 pub(crate) mod git_tokens;
30 mod guest_checkout;
31 mod imports;
32 pub(crate) mod internal;
33 pub(crate) mod items;
34 pub(crate) mod license_keys;
35 mod links;
36 mod passkeys;
37 mod preview;
38 mod project_sections;
39 mod projects;
40 mod promo_codes;
41 mod repo_notifications;
42 mod reports;
43 pub(crate) mod ssh_keys;
44 mod subscriptions;
45 mod tags;
46 pub(crate) mod totp;
47 mod users;
48 mod validate;
49 mod wishlists;
50
51 use axum::{
52 Json,
53 extract::{Request, State},
54 middleware::Next,
55 response::{IntoResponse, Response},
56 routing::{get, options},
57 };
58 use serde::Serialize;
59 use serde_json::json;
60 use tower_governor::GovernorLayer;
61
62 use sqlx::PgPool;
63
64 use crate::{
65 AppState, constants,
66 csrf::{
67 CsrfRouter, delete_csrf, delete_csrf_skip, post_csrf, post_csrf_skip, put_csrf,
68 put_csrf_skip,
69 },
70 db::{self, BlogPostId, ItemId, ProjectId, ProjectType, UserId},
71 error::{ApiErrorMessage, AppError, Result},
72 };
73
74 const LICENSE_BEARER_SKIP: &str = "license API: bearer license key, no session";
75 const GUEST_CHECKOUT_SKIP: &str = "guest checkout: pre-auth, no session";
76 const CSP_REPORT_SKIP: &str = "CSP report: browser-posted, no session";
77 const GIT_NOTES_SKIP: &str =
78 "git notes API: push-scoped personal access token, session cookie rejected";
79
80 /// Fetch a project and verify the user owns it. Shared by all ownership checks
81 /// that go through a project (items, blog posts, direct project access).
82 pub(super) async fn verify_project_ownership(
83 db: &sqlx::PgPool,
84 project_id: ProjectId,
85 user_id: UserId,
86 ) -> Result<db::DbProject> {
87 let project = db::projects::get_project_by_id(db, project_id)
88 .await?
89 .ok_or(AppError::NotFound)?;
90 if project.user_id != user_id {
91 return Err(AppError::Forbidden);
92 }
93 Ok(project)
94 }
95
96 pub(super) async fn verify_item_ownership(
97 db: &sqlx::PgPool,
98 item_id: ItemId,
99 user_id: UserId,
100 ) -> Result<(db::DbItem, db::DbProject)> {
101 let item = db::items::get_item_by_id(db, item_id)
102 .await?
103 .ok_or(AppError::NotFound)?;
104 let project = verify_project_ownership(db, item.project_id, user_id).await?;
105 Ok((item, project))
106 }
107
108 pub(super) async fn verify_blog_post_ownership(
109 db: &sqlx::PgPool,
110 blog_post_id: BlogPostId,
111 user_id: UserId,
112 ) -> Result<db::DbBlogPost> {
113 let post = db::blog_posts::get_blog_post_by_id(db, blog_post_id)
114 .await?
115 .ok_or(AppError::NotFound)?;
116 verify_project_ownership(db, post.project_id, user_id).await?;
117 Ok(post)
118 }
119
120 /// Middleware that converts HTML error responses into JSON on API routes.
121 ///
122 /// When `AppError::into_response()` fires it stashes an [`ApiErrorMessage`] in
123 /// the response extensions. This layer checks for that extension and, if
124 /// present, replaces the HTML body with `{"error": "..."}` while preserving the
125 /// original status code. Page routes never hit this layer, so they keep
126 /// getting the full HTML error template.
127 async fn json_error_layer(req: Request, next: Next) -> Response {
128 let response = next.run(req).await;
129 if let Some(ApiErrorMessage(msg)) = response.extensions().get::<ApiErrorMessage>().cloned() {
130 let status = response.status();
131 return (status, Json(json!({"error": msg}))).into_response();
132 }
133 response
134 }
135
136 // --- Public project listing (no auth) ---
137
138 #[derive(Serialize)]
139 struct PublicProject {
140 slug: String,
141 title: String,
142 description: Option<String>,
143 project_type: ProjectType,
144 username: String,
145 item_count: i64,
146 }
147
148 #[tracing::instrument(skip_all, name = "api::public_projects")]
149 async fn public_projects(State(db): State<PgPool>) -> Result<impl IntoResponse> {
150 let rows = db::discover::discover_projects(&db, None, None, None, false, 50, 0).await?;
151 let data: Vec<PublicProject> = rows
152 .into_iter()
153 .map(|r| PublicProject {
154 slug: r.slug.to_string(),
155 title: r.title,
156 description: r.description,
157 project_type: r.project_type,
158 username: r.username.to_string(),
159 item_count: r.item_count,
160 })
161 .collect();
162 Ok(Json(json!({ "data": data })))
163 }
164
165 /// Register all JSON API routes for projects, items, links, tags, and account management.
166 ///
167 /// Routes are split across sub-routers, each ending in its own
168 /// `GovernorLayer` with its own per-IP limit. Every tier is throttled, reads
169 /// included; the numbers live in the `constants::API_*_RATE_LIMIT_*` each
170 /// builder reads.
171 pub fn api_routes(limits: constants::RateLimits) -> CsrfRouter<AppState> {
172 let write_rate_limit = crate::helpers::rate_limiter_ms(
173 constants::API_WRITE_RATE_LIMIT_MS,
174 constants::API_WRITE_RATE_LIMIT_BURST,
175 );
176 let export_rate_limit = crate::helpers::rate_limiter_per_sec(
177 constants::API_EXPORT_RATE_LIMIT_PER_SEC,
178 constants::API_EXPORT_RATE_LIMIT_BURST,
179 );
180
181 // Write routes, rate limited
182 let write_routes = CsrfRouter::new()
183 // User routes
184 .route("/api/users/me", put_csrf(users::update_profile))
185 .route("/api/users/me/password", put_csrf(users::update_password))
186 .route(
187 "/api/users/me/preferences",
188 put_csrf(users::update_preferences),
189 )
190 .route(
191 "/api/users/me/stripe",
192 delete_csrf(users::disconnect_stripe),
193 )
194 .route(
195 "/api/users/me/stripe-tax",
196 put_csrf(users::toggle_stripe_tax),
197 )
198 .route("/api/users/me/theme", put_csrf(users::update_profile_theme))
199 .route(
200 "/api/users/me/console-theme",
201 put_csrf(users::update_console_theme),
202 )
203 .route("/api/users/me", delete_csrf(users::delete_account))
204 .route(
205 "/api/users/me/deactivate",
206 post_csrf(users::deactivate_account),
207 )
208 .route(
209 "/api/users/me/reactivate",
210 post_csrf(users::reactivate_account),
211 )
212 .route(
213 "/api/users/me/pause-creator",
214 post_csrf(users::pause_creator),
215 )
216 // Broadcast
217 .route("/api/broadcast", post_csrf(users::broadcast_send))
218 .route(
219 "/api/support/ticket",
220 post_csrf(users::submit_support_ticket),
221 )
222 // Project routes
223 .route("/api/projects", post_csrf(projects::create_project))
224 .route("/api/projects/{id}", put_csrf(projects::update_project))
225 .route(
226 "/api/projects/{id}/theme",
227 put_csrf(projects::update_project_theme),
228 )
229 .route("/api/projects/{id}", delete_csrf(projects::delete_project))
230 // Git repo management
231 .route("/api/repos", post_csrf(projects::create_repo))
232 .route(
233 "/api/repos/{id}/visibility",
234 put_csrf(projects::update_repo_visibility),
235 )
236 .route_get(
237 "/api/repos/{id}/collaborators",
238 get(projects::list_repo_collaborators),
239 )
240 .route(
241 "/api/repos/{id}/collaborators",
242 post_csrf(projects::add_repo_collaborator),
243 )
244 .route(
245 "/api/repos/{repo_id}/collaborators/{user_id}",
246 delete_csrf(projects::remove_repo_collaborator),
247 )
248 .route("/api/projects/{id}/repos", post_csrf(projects::link_repo))
249 .route(
250 "/api/projects/{id}/repos/{repo_name}",
251 delete_csrf(projects::unlink_repo),
252 )
253 // Project members
254 .route(
255 "/api/projects/{id}/members",
256 post_csrf(projects::add_project_member),
257 )
258 .route(
259 "/api/projects/{project_id}/members/{user_id}",
260 delete_csrf(projects::remove_project_member),
261 )
262 // A collaborator answering their own invitation. Separate from the two
263 // above, which are the owner's.
264 .route(
265 "/api/projects/{id}/members/accept",
266 post_csrf(projects::accept_split_invitation),
267 )
268 .route(
269 "/api/projects/{id}/members/decline",
270 post_csrf(projects::decline_split_invitation),
271 )
272 // Item routes
273 .route("/api/projects/{id}/items", post_csrf(items::create_item))
274 .route("/api/items/{id}", put_csrf(items::update_item))
275 .route("/api/items/{id}", delete_csrf(items::delete_item))
276 .route(
277 "/api/items/{id}/duplicate",
278 post_csrf(items::duplicate_item),
279 )
280 // Bulk item operations
281 .route("/api/items/bulk/publish", post_csrf(items::bulk_publish))
282 .route(
283 "/api/items/bulk/unpublish",
284 post_csrf(items::bulk_unpublish),
285 )
286 .route("/api/items/bulk/delete", post_csrf(items::bulk_delete))
287 .route("/api/items/bulk/price", post_csrf(items::bulk_price))
288 .route("/api/items/bulk/tag", post_csrf(items::bulk_tag))
289 .route("/api/items/{id}/move", put_csrf(items::move_item))
290 // Bundle management
291 .route("/api/items/{id}/bundle/add", post_csrf(items::bundle_add))
292 .route(
293 "/api/items/{id}/bundle/create-child",
294 post_csrf(items::bundle_create_child),
295 )
296 .route(
297 "/api/items/{id}/bundle/{child_id}",
298 delete_csrf(items::bundle_remove),
299 )
300 .route(
301 "/api/items/{id}/bundle/{child_id}/listed",
302 put_csrf(items::bundle_toggle_listed),
303 )
304 // Refund
305 .route(
306 "/api/items/{id}/refund",
307 post_csrf(items::refund_transaction),
308 )
309 .route("/api/items/{id}/restore", post_csrf(items::restore_item))
310 // Tag routes (HTMX)
311 .route("/api/items/{id}/tags", post_csrf(items::add_tag))
312 .route(
313 "/api/items/{id}/tags/{tag_id}",
314 delete_csrf(items::remove_tag),
315 )
316 .route(
317 "/api/items/{id}/primary-tag",
318 put_csrf(items::set_primary_tag),
319 )
320 // Text content route
321 .route("/api/items/{id}/text", put_csrf(items::update_item_text))
322 // Version routes
323 .route("/api/items/{id}/versions", post_csrf(items::create_version))
324 .route(
325 "/api/items/{id}/versions/{version_id}",
326 delete_csrf(items::delete_version),
327 )
328 // Custom link routes
329 .route("/api/links", post_csrf(links::create_link))
330 .route("/api/links/{id}", put_csrf(links::update_link))
331 .route("/api/links/{id}", delete_csrf(links::delete_link))
332 .route("/api/links/reorder", put_csrf(links::reorder_links))
333 // Chapter routes
334 .route("/api/items/{id}/chapters", post_csrf(items::create_chapter))
335 .route("/api/chapters/{id}", put_csrf(items::update_chapter))
336 .route("/api/chapters/{id}", delete_csrf(items::delete_chapter))
337 // Section routes
338 .route("/api/items/{id}/sections", post_csrf(items::create_section))
339 .route("/api/sections/{id}", put_csrf(items::update_section))
340 .route("/api/sections/{id}", delete_csrf(items::delete_section))
341 .route(
342 "/api/items/{id}/sections/reorder",
343 put_csrf(items::reorder_sections),
344 )
345 // Project section routes
346 .route(
347 "/api/projects/{id}/sections",
348 post_csrf(project_sections::create_section),
349 )
350 .route(
351 "/api/project-sections/{id}",
352 put_csrf(project_sections::update_section),
353 )
354 .route(
355 "/api/project-sections/{id}",
356 delete_csrf(project_sections::delete_section),
357 )
358 .route(
359 "/api/projects/{id}/sections/reorder",
360 put_csrf(project_sections::reorder_sections),
361 )
362 // Library routes
363 .route(
364 "/api/library/add/{item_id}",
365 post_csrf(users::add_to_library),
366 )
367 .route(
368 "/api/library/remove/{item_id}",
369 delete_csrf(users::remove_from_library),
370 )
371 // Contact sharing revocation
372 .route(
373 "/api/contacts/{seller_id}",
374 delete_csrf(users::revoke_contact),
375 )
376 // Waitlist
377 .route("/api/waitlist/apply", post_csrf(users::waitlist_apply))
378 // Email verification
379 .route(
380 "/api/resend-verification",
381 post_csrf(users::resend_verification),
382 )
383 // Account management
384 .route(
385 "/api/account/request-deletion",
386 post_csrf(users::request_account_deletion),
387 )
388 // Suspension appeal
389 .route("/api/users/me/appeal", post_csrf(users::submit_appeal))
390 // Session management
391 .route(
392 "/api/users/me/sessions/{id}",
393 delete_csrf(users::revoke_session),
394 )
395 .route(
396 "/api/users/me/sessions",
397 delete_csrf(users::revoke_other_sessions),
398 )
399 // Blog routes
400 .route("/api/projects/{id}/blog", post_csrf(blog::create_blog_post))
401 .route("/api/blog/{id}", put_csrf(blog::update_blog_post))
402 .route("/api/blog/{id}", delete_csrf(blog::delete_blog_post))
403 // License key management (creator)
404 .route(
405 "/api/items/{id}/license-settings",
406 put_csrf(license_keys::update_license_settings),
407 )
408 .route(
409 "/api/items/{id}/keys",
410 post_csrf(license_keys::generate_key),
411 )
412 .route("/api/keys/{id}/revoke", post_csrf(license_keys::revoke_key))
413 // Promo code management (creator)
414 .route(
415 "/api/promo-codes",
416 post_csrf(promo_codes::create_promo_code),
417 )
418 .route_get("/api/promo-codes", get(promo_codes::list_promo_codes))
419 .route(
420 "/api/promo-codes/expired",
421 delete_csrf(promo_codes::delete_expired_promo_codes),
422 )
423 .route(
424 "/api/promo-codes/{id}",
425 put_csrf(promo_codes::update_promo_code),
426 )
427 .route(
428 "/api/promo-codes/{id}",
429 delete_csrf(promo_codes::delete_promo_code),
430 )
431 .route_get(
432 "/api/promo-codes/{id}/redemptions",
433 get(promo_codes::list_redemptions),
434 )
435 // Promo code claim (buyer, free_access codes)
436 .route(
437 "/api/promo-codes/claim",
438 post_csrf(promo_codes::claim_promo_code),
439 )
440 // Subscription tier management (creator)
441 .route(
442 "/api/projects/{id}/tiers",
443 post_csrf(subscriptions::create_tier),
444 )
445 .route("/api/tiers/{id}", put_csrf(subscriptions::update_tier))
446 .route("/api/tiers/{id}", delete_csrf(subscriptions::delete_tier))
447 // Follow system
448 .route(
449 "/api/follow/{target_type}/{target_id}",
450 post_csrf(follows::follow_target),
451 )
452 .route(
453 "/api/follow/{target_type}/{target_id}",
454 delete_csrf(follows::unfollow_target),
455 )
456 // Category management
457 .route("/api/categories", post_csrf(categories::create_category))
458 // TOTP 2FA management (setup only; the password/code-verifying mutations
459 // move to a stricter auth-rate-limited sub-router below).
460 .route("/api/users/me/totp/setup", post_csrf(totp::setup))
461 // Passkey management
462 .route(
463 "/api/users/me/passkeys/register/start",
464 post_csrf(passkeys::register_start),
465 )
466 .route(
467 "/api/users/me/passkeys/register/finish",
468 post_csrf(passkeys::register_finish),
469 )
470 .route("/api/users/me/passkeys/{id}", put_csrf(passkeys::rename))
471 .route("/api/users/me/passkeys/{id}", delete_csrf(passkeys::delete))
472 // Content insertion management
473 .route(
474 "/api/users/me/insertions/presign",
475 post_csrf(content_insertions::presign_insertion),
476 )
477 .route(
478 "/api/users/me/insertions/confirm",
479 post_csrf(content_insertions::confirm_insertion),
480 )
481 .route(
482 "/api/insertions/{id}",
483 put_csrf(content_insertions::rename_insertion),
484 )
485 .route(
486 "/api/insertions/{id}",
487 delete_csrf(content_insertions::delete_insertion),
488 )
489 // Content insertion placements
490 .route(
491 "/api/items/{id}/insertions",
492 post_csrf(content_insertions::create_placement),
493 )
494 .route(
495 "/api/item-insertions/{id}",
496 delete_csrf(content_insertions::delete_placement),
497 )
498 // SSH key management
499 .route_get("/api/users/me/ssh-keys", get(ssh_keys::list_keys))
500 .route("/api/users/me/ssh-keys", post_csrf(ssh_keys::add_key))
501 .route(
502 "/api/users/me/ssh-keys/{id}",
503 delete_csrf(ssh_keys::delete_key),
504 )
505 // Git access tokens (HTTPS)
506 .route("/api/users/me/git-tokens", post_csrf(git_tokens::create))
507 .route(
508 "/api/users/me/git-tokens/{id}",
509 delete_csrf(git_tokens::revoke),
510 )
511 // Reports
512 .route("/api/reports", post_csrf(reports::submit_report))
513 // Collections
514 .route(
515 "/api/collections",
516 post_csrf(collections::create_collection),
517 )
518 .route(
519 "/api/collections/{id}",
520 put_csrf(collections::update_collection),
521 )
522 .route(
523 "/api/collections/{id}",
524 delete_csrf(collections::delete_collection),
525 )
526 .route(
527 "/api/collections/{id}/items/{item_id}",
528 post_csrf(collections::add_item),
529 )
530 .route(
531 "/api/collections/{id}/items/{item_id}",
532 delete_csrf(collections::remove_item),
533 )
534 .route(
535 "/api/collections/{id}/items/reorder",
536 put_csrf(collections::reorder_items),
537 )
538 // Wishlists
539 .route(
540 "/api/wishlists/{item_id}",
541 post_csrf(wishlists::toggle_wishlist),
542 )
543 // Cart
544 .route("/api/cart/{item_id}", post_csrf(cart::toggle_cart))
545 .route("/api/cart/{item_id}", put_csrf(cart::update_cart_amount))
546 .route("/api/cart/{item_id}", delete_csrf(cart::remove_from_cart))
547 // Custom domains
548 .route("/api/domains", post_csrf(domains::add_domain))
549 .route("/api/domains/verify", post_csrf(domains::verify_domain))
550 .route("/api/domains/{id}", delete_csrf(domains::remove_domain))
551 // Invite codes
552 .route("/api/invites/create", post_csrf(users::create_invite))
553 // Git notes (write). CSRF-skipped because the caller is a script rather
554 // than a page MNW rendered, so it holds no token to send; the handlers
555 // require a push-scoped personal access token and reject a session
556 // cookie, which is the same seal `receive-pack` uses for the same
557 // reason. The `origin_gate` still wraps these.
558 .route(
559 "/api/git/{owner}/{repo}/notes/{target}",
560 put_csrf_skip(GIT_NOTES_SKIP, git_notes::put_note),
561 )
562 .route(
563 "/api/git/{owner}/{repo}/notes/{target}",
564 delete_csrf_skip(GIT_NOTES_SKIP, git_notes::delete_note),
565 )
566 // Per-repository issue notifications (mailing-list step 6)
567 .route(
568 "/api/repos/notifications",
569 post_csrf(repo_notifications::set_repo_notifications),
570 )
571 .route_layer(GovernorLayer::new(write_rate_limit));
572
573 // Password/code-verifying TOTP mutations, strict auth-strength rate limit
574 // (matching login), not the looser API-write limit, so confirm-code and
575 // disable/regenerate password checks can't be ground (ultra-fuzz Run 10 Sec M1).
576 let totp_sensitive_rate_limit =
577 crate::helpers::rate_limiter_ms(limits.auth_ms, limits.auth_burst);
578 let totp_sensitive_routes = CsrfRouter::new()
579 .route("/api/users/me/totp/confirm", post_csrf(totp::confirm))
580 .route("/api/users/me/totp/disable", post_csrf(totp::disable))
581 .route(
582 "/api/users/me/totp/backup-codes",
583 post_csrf(totp::regenerate_backup_codes),
584 )
585 .route_layer(GovernorLayer::new(totp_sensitive_rate_limit));
586
587 // Export routes, stricter rate limit
588 let export_routes = CsrfRouter::new()
589 .route("/api/export/projects", post_csrf(exports::export_projects))
590 .route("/api/export/sales", post_csrf(exports::export_sales))
591 .route(
592 "/api/export/purchases",
593 post_csrf(exports::export_purchases),
594 )
595 .route("/api/export/splits", post_csrf(exports::export_splits))
596 .route(
597 "/api/export/followers",
598 post_csrf(exports::export_followers),
599 )
600 .route(
601 "/api/export/subscriptions",
602 post_csrf(exports::export_subscriptions),
603 )
604 .route("/api/export/content", post_csrf(exports::export_content))
605 .route("/api/export/contacts", post_csrf(exports::export_contacts))
606 .route_layer(GovernorLayer::new(export_rate_limit));
607
608 let key_rate_limit = crate::helpers::rate_limiter_ms(
609 constants::LICENSE_KEY_RATE_LIMIT_MS,
610 constants::LICENSE_KEY_RATE_LIMIT_BURST,
611 );
612
613 let key_routes = CsrfRouter::new()
614 .route(
615 "/api/keys/validate",
616 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::validate_key),
617 )
618 .route(
619 "/api/v1/keys/validate",
620 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::validate_key),
621 )
622 .route(
623 "/api/keys/deactivate",
624 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::deactivate_key),
625 )
626 .route(
627 "/api/v1/keys/deactivate",
628 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::deactivate_key),
629 )
630 // Key in the POST body keeps the purchase-proof secret out of access
631 // logs. The GET-path forms below are deprecated but kept for SDK
632 // consumers that predate this endpoint.
633 .route(
634 "/api/keys/status",
635 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::key_status_post),
636 )
637 .route(
638 "/api/v1/keys/status",
639 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::key_status_post),
640 )
641 .route_get("/api/keys/{key_code}/status", get(license_keys::key_status))
642 .route_get(
643 "/api/v1/keys/{key_code}/status",
644 get(license_keys::key_status),
645 )
646 .route(
647 "/api/v1/license/verify",
648 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::license_verify),
649 )
650 .route(
651 "/api/v1/license/deactivate",
652 post_csrf_skip(LICENSE_BEARER_SKIP, license_keys::license_deactivate),
653 )
654 .route_layer(GovernorLayer::new(key_rate_limit));
655
656 let read_rate_limit = crate::helpers::rate_limiter_ms(
657 constants::API_READ_RATE_LIMIT_MS,
658 constants::API_READ_RATE_LIMIT_BURST,
659 );
660
661 // Read routes
662 let read_routes = CsrfRouter::new()
663 .route_get("/api/public/projects", get(public_projects))
664 .route_get("/api/v1/public/projects", get(public_projects))
665 .route_get("/api/projects", get(projects::list_projects))
666 .route_get("/api/items/{id}/versions", get(items::list_versions))
667 .route_get("/api/items/{id}/chapters", get(items::list_chapters))
668 .route_get("/api/items/{id}/sections", get(items::list_sections))
669 .route_get("/api/items/{id}/keys", get(license_keys::list_keys))
670 .route_get(
671 "/api/projects/{id}/sections",
672 get(project_sections::list_sections),
673 )
674 .route_get("/api/projects/{id}/blog", get(blog::list_blog_posts))
675 .route_get("/api/blog/{id}", get(blog::get_blog_post))
676 .route_get("/api/tags/search", get(tags::search_tags))
677 .route_get("/api/categories/search", get(categories::search_categories))
678 .route_get("/api/items/{id}/tag-suggestions", get(tags::suggest_tags))
679 .route_get("/api/projects/{id}/tiers", get(subscriptions::list_tiers))
680 // TOTP status (HTMX partial for dashboard)
681 .route_get("/api/users/me/totp/status", get(totp::status))
682 // Passkey list (HTMX partial for dashboard)
683 .route_get("/api/users/me/passkeys", get(passkeys::list))
684 // SSH key list (HTMX partial for dashboard)
685 .route_get("/api/users/me/ssh-keys/list", get(ssh_keys::list_keys_html))
686 .route_get("/api/users/me/git-tokens/list", get(git_tokens::list_html))
687 // Content insertion list (HTMX partials for dashboard)
688 .route_get(
689 "/api/users/me/insertions",
690 get(content_insertions::list_insertions),
691 )
692 .route_get(
693 "/api/items/{id}/insertions",
694 get(content_insertions::list_placements),
695 )
696 // Collections (read)
697 .route_get(
698 "/api/collections/for-item/{item_id}",
699 get(collections::collections_for_item),
700 )
701 // Custom domains (read)
702 .route_get("/api/domains", get(domains::get_domain))
703 .route_get("/api/domains/caddy-ask", get(domains::caddy_ask))
704 .route_get("/api/restart-status", get(internal::restart_status))
705 // Git notes (read). `search` is a static segment and an object id is 40
706 // or 64 hex characters, so the two never shadow each other.
707 .route_get(
708 "/api/git/{owner}/{repo}/notes",
709 get(git_notes::list_namespaces),
710 )
711 .route_get(
712 "/api/git/{owner}/{repo}/notes/search",
713 get(git_notes::search_notes),
714 )
715 .route_get(
716 "/api/git/{owner}/{repo}/notes/{target}",
717 get(git_notes::get_note),
718 )
719 // Cart (read)
720 .route_get("/api/cart/count", get(cart::cart_count))
721 // Import system (read)
722 .route_get("/api/users/me/import/{id}", get(imports::get_import_status))
723 .route_get("/api/users/me/imports", get(imports::list_imports))
724 // License text (public)
725 .route_get(
726 "/api/items/{id}/license.txt",
727 get(license_keys::license_text),
728 )
729 .route_get(
730 "/api/v1/items/{id}/license.txt",
731 get(license_keys::license_text),
732 )
733 .route_layer(GovernorLayer::new(read_rate_limit));
734
735 let validate_rate_limit = crate::helpers::rate_limiter_per_sec(
736 constants::VALIDATE_RATE_LIMIT_PER_SEC,
737 constants::VALIDATE_RATE_LIMIT_BURST,
738 );
739
740 let validate_routes = CsrfRouter::new()
741 .route(
742 "/api/validate/project-slug",
743 post_csrf(validate::validate_project_slug),
744 )
745 .route(
746 "/api/validate/collection-slug",
747 post_csrf(validate::validate_collection_slug),
748 )
749 .route(
750 "/api/validate/blog-slug",
751 post_csrf(validate::validate_blog_slug),
752 )
753 .route_layer(GovernorLayer::new(validate_rate_limit));
754
755 // Markdown preview: its own group because it is neither a write nor a
756 // validation. Rate limited on its own budget, and behind CSRF and a session
757 // like every other POST here, because the media rewriting is per-creator.
758 let preview_routes = CsrfRouter::new()
759 .route(
760 "/api/preview/markdown",
761 post_csrf(preview::preview_markdown),
762 )
763 .route_layer(GovernorLayer::new(crate::helpers::rate_limiter_per_sec(
764 constants::PREVIEW_RATE_LIMIT_PER_SEC,
765 constants::PREVIEW_RATE_LIMIT_BURST,
766 )));
767
768 // Import route needs a higher body limit (base64-encoded CSV up to 10 MB
769 // ≈ 14 MB encoded). The global 1 MB RequestBodyLimitLayer would reject it,
770 // so we override with a per-route layer.
771 let import_routes = CsrfRouter::new()
772 .route("/api/users/me/import", post_csrf(imports::start_import))
773 .layer(axum::extract::DefaultBodyLimit::max(15 * 1024 * 1024))
774 .route_layer(GovernorLayer::new(crate::helpers::rate_limiter_ms(
775 constants::API_WRITE_RATE_LIMIT_MS,
776 constants::API_WRITE_RATE_LIMIT_BURST,
777 )));
778
779 // Guest checkout routes, public, no auth, CORS-enabled, stricter rate limit
780 let guest_checkout_rate_limit = crate::helpers::rate_limiter_per_sec(
781 constants::GUEST_CHECKOUT_RATE_LIMIT_PER_SEC,
782 constants::GUEST_CHECKOUT_RATE_LIMIT_BURST,
783 );
784 let guest_routes = CsrfRouter::new()
785 .route(
786 "/api/checkout/guest/{item_id}",
787 post_csrf_skip(GUEST_CHECKOUT_SKIP, guest_checkout::create_guest_checkout),
788 )
789 .route_get(
790 "/api/checkout/guest/{item_id}",
791 options(guest_checkout::guest_checkout_preflight),
792 )
793 .route(
794 "/api/checkout/guest-free/{item_id}",
795 post_csrf_skip(GUEST_CHECKOUT_SKIP, guest_checkout::claim_free_guest),
796 )
797 .route(
798 "/api/purchases/claim",
799 post_csrf(guest_checkout::claim_purchase),
800 )
801 .route_layer(GovernorLayer::new(guest_checkout_rate_limit));
802
803 // Guest download route, separate, more lenient per-IP rate limit. Unauth'd
804 // and token-gated; the throttle is defense-in-depth against anonymous flooding
805 // (token entropy already makes enumeration impractical).
806 let download_rate_limit = crate::helpers::rate_limiter_per_sec(
807 constants::GUEST_DOWNLOAD_RATE_LIMIT_PER_SEC,
808 constants::GUEST_DOWNLOAD_RATE_LIMIT_BURST,
809 );
810 let download_routes = CsrfRouter::new()
811 .route_get("/download/{token}", get(guest_checkout::guest_download))
812 .route_layer(GovernorLayer::new(download_rate_limit));
813
814 // CSP violation intake. Posted by the browser with no session and no CSRF
815 // token, so it skips CSRF by necessity; the compensating controls are the
816 // per-IP throttle and the body cap. An enforced violation reaches
817 // `security_signals::note_csp_violation`, which persists an alert row and
818 // mails the operator, so this endpoint does write. Dedup is once per
819 // distinct blocked URI per day, which bounds the writes.
820 let csp_report_rate_limit = crate::helpers::rate_limiter_per_sec(
821 constants::CSP_REPORT_RATE_LIMIT_PER_SEC,
822 constants::CSP_REPORT_RATE_LIMIT_BURST,
823 );
824 let csp_report_routes = CsrfRouter::new()
825 .route(
826 "/api/csp-report",
827 post_csrf_skip(CSP_REPORT_SKIP, csp_report::report_csp_violation),
828 )
829 .layer(axum::extract::DefaultBodyLimit::max(
830 constants::CSP_REPORT_BODY_LIMIT_BYTES,
831 ))
832 .route_layer(GovernorLayer::new(csp_report_rate_limit));
833
834 write_routes
835 .merge(csp_report_routes)
836 .merge(totp_sensitive_routes)
837 .merge(export_routes)
838 .merge(key_routes)
839 .merge(validate_routes)
840 .merge(preview_routes)
841 .merge(read_routes)
842 .merge(import_routes)
843 .merge(guest_routes)
844 .merge(download_routes)
845 .merge(internal::internal_routes())
846 .layer(axum::middleware::from_fn(json_error_layer))
847 }
848