Skip to main content

max / makenotwork

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