Skip to main content

replybots/
lib.rs

1//! # replybots
2//!
3//! WhatsApp auto-reply platform for small businesses.
4
5use worker::*;
6
7mod ai;
8mod api;
9mod billing;
10mod channel;
11mod crypto;
12mod dev_bypass;
13mod email;
14mod escalations;
15mod handlers;
16mod helpers;
17mod locale;
18mod pipeline;
19mod prompt;
20mod risk;
21mod safety;
22mod shell;
23mod storage;
24mod types;
25mod whatsapp;
26
27pub use types::*;
28
29/// Meta Graph API version used across all Facebook/WhatsApp API calls.
30pub const META_API_VERSION: &str = "v21.0";
31
32const LOGO_SVG: &str = include_str!("../assets/logo.svg");
33const WEBMANIFEST: &str = include_str!("../assets/site.webmanifest");
34const BROWSERCONFIG: &str = include_str!("../assets/browserconfig.xml");
35const FAVICON_16: &[u8] = include_bytes!("../assets/favicon-16.png");
36const FAVICON_32: &[u8] = include_bytes!("../assets/favicon-32.png");
37const APPLE_TOUCH_ICON: &[u8] = include_bytes!("../assets/apple-touch-icon.png");
38const LOGO_192: &[u8] = include_bytes!("../assets/logo-192.png");
39const LOGO_512: &[u8] = include_bytes!("../assets/logo-512.png");
40const MSTILE_150: &[u8] = include_bytes!("../assets/mstile-150x150.png");
41
42fn add_security_headers(resp: &mut Response, is_dev: bool) -> Result<()> {
43    let headers = resp.headers_mut();
44    headers.set("X-Frame-Options", "DENY")?;
45    headers.set("X-Content-Type-Options", "nosniff")?;
46    headers.set("Referrer-Policy", "strict-origin-when-cross-origin")?;
47    let (img_extra, form_action_extra) = if is_dev {
48        (
49            " blob:",
50            " http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:*",
51        )
52    } else {
53        ("", "")
54    };
55    let csp = format!(
56        "default-src 'self'; \
57         script-src 'self' https://checkout.razorpay.com https://connect.facebook.net; \
58         style-src 'self' 'unsafe-inline'; \
59         img-src 'self' data: https:{img_extra}; \
60         connect-src 'self' https://www.facebook.com https://graph.facebook.com https://*.facebook.com https://api.razorpay.com; \
61         frame-src https://www.facebook.com https://*.facebook.com https://api.razorpay.com https://checkout.razorpay.com; \
62         base-uri 'self'; \
63         form-action 'self'{form_action_extra}; \
64         object-src 'none'"
65    );
66    headers.set("Content-Security-Policy", &csp)?;
67    Ok(())
68}
69
70fn serve_text(body: &str, content_type: &str) -> Result<Response> {
71    let headers = Headers::new();
72    headers.set("Content-Type", content_type)?;
73    headers.set("Cache-Control", "public, max-age=31536000")?;
74    Ok(Response::ok(body)?.with_headers(headers))
75}
76
77fn serve_png(body: &[u8]) -> Result<Response> {
78    let headers = Headers::new();
79    headers.set("Content-Type", "image/png")?;
80    headers.set("Cache-Control", "public, max-age=31536000")?;
81    Ok(Response::from_bytes(body.to_vec())?.with_headers(headers))
82}
83
84#[event(fetch)]
85async fn fetch(req: Request, env: Env, ctx: Context) -> Result<Response> {
86    console_error_panic_hook::set_once();
87    let is_dev = dev_bypass::active(&env);
88    let mut resp = handle_request(req, env, &ctx).await?;
89    let is_html = resp
90        .headers()
91        .get("Content-Type")
92        .ok()
93        .flatten()
94        .is_some_and(|ct| ct.contains("text/html"));
95    if is_html {
96        add_security_headers(&mut resp, is_dev)?;
97    }
98    Ok(resp)
99}
100
101fn serve_shell(status: u16) -> Result<Response> {
102    let headers = Headers::new();
103    headers.set("Content-Type", "text/html; charset=utf-8")?;
104    headers.set("Cache-Control", "no-store")?;
105    Ok(Response::ok(shell::html())?
106        .with_status(status)
107        .with_headers(headers))
108}
109
110fn is_app_route(path: &str) -> bool {
111    matches!(
112        path,
113        "/" | "/index.html"
114            | "/pricing"
115            | "/features"
116            | "/terms"
117            | "/privacy"
118            | "/login"
119            | "/wizard"
120            | "/dashboard"
121            | "/dashboard/channels"
122            | "/dashboard/billing"
123            | "/dashboard/settings"
124    ) || path.starts_with("/wizard/")
125}
126
127async fn handle_request(req: Request, env: Env, ctx: &Context) -> Result<Response> {
128    let url = req.url()?;
129    let path = url.path();
130    let method = req.method();
131
132    let public_base = env
133        .var("PUBLIC_BASE_URL")
134        .map(|v| v.to_string())
135        .unwrap_or_default();
136    if public_base.is_empty() {
137        console_log!("PUBLIC_BASE_URL is not set");
138        return Response::error(
139            "Service unavailable: PUBLIC_BASE_URL is not configured",
140            503,
141        );
142    }
143
144    let host = url.host_str().unwrap_or("");
145    let req_base = format!("{}://{}", url.scheme(), host);
146
147    match path {
148        "/robots.txt" => {
149            let body = format!(
150                "User-agent: *\nAllow: /\nAllow: /features\nAllow: /pricing\nAllow: /terms\nAllow: /privacy\nDisallow: /api\nDisallow: /dashboard\nDisallow: /wizard\nDisallow: /auth\nDisallow: /webhook\nDisallow: /whatsapp\n\nSitemap: {req_base}/sitemap.txt\n"
151            );
152            return serve_text(&body, "text/plain");
153        }
154        "/sitemap.txt" => {
155            let body = format!(
156                "{req_base}/\n{req_base}/features\n{req_base}/pricing\n{req_base}/terms\n{req_base}/privacy\n"
157            );
158            return serve_text(&body, "text/plain");
159        }
160        "/logo.svg" => return serve_text(LOGO_SVG, "image/svg+xml"),
161        "/site.webmanifest" => return serve_text(WEBMANIFEST, "application/manifest+json"),
162        "/browserconfig.xml" => return serve_text(BROWSERCONFIG, "application/xml"),
163        "/favicon-16.png" => return serve_png(FAVICON_16),
164        "/favicon-32.png" => return serve_png(FAVICON_32),
165        "/apple-touch-icon.png" => return serve_png(APPLE_TOUCH_ICON),
166        "/logo-192.png" => return serve_png(LOGO_192),
167        "/logo-512.png" => return serve_png(LOGO_512),
168        "/mstile-150x150.png" => return serve_png(MSTILE_150),
169        "/health" => return handlers::health::handle_health(req, env).await,
170        _ => {}
171    }
172
173    if path == "/api" || path.starts_with("/api/") {
174        return api::handle(req, env, path).await;
175    }
176
177    if path == "/webhook/razorpay" && method == Method::Post {
178        return billing::webhook::handle_razorpay_webhook(req, env).await;
179    }
180    if path.starts_with("/webhook/") {
181        return handlers::handle_webhook(req, env, ctx, path, method).await;
182    }
183
184    if path == "/data-deletion" {
185        return handlers::handle_data_deletion(req, env, method).await;
186    }
187
188    let needs_essentials = path.starts_with("/auth") || path.starts_with("/whatsapp/signup");
189    if needs_essentials && !handlers::health::essentials_missing(&env).is_empty() {
190        let headers = Headers::new();
191        headers.set("Retry-After", "60")?;
192        headers.set("Cache-Control", "no-store")?;
193        return Ok(Response::error("Temporarily unavailable", 503)?.with_headers(headers));
194    }
195
196    if path.starts_with("/auth/") {
197        return handlers::handle_auth(req, env, path, method).await;
198    }
199
200    if path.starts_with("/whatsapp/signup/") {
201        return handlers::handle_whatsapp_signup(req, env, path, method).await;
202    }
203
204    if is_app_route(path) {
205        return serve_shell(200);
206    }
207
208    serve_shell(404)
209}