firecrawl-local 0.1.0

Firecrawl Local: scrape, crawl and map on your own machine from one binary, with a hand-off to Firecrawl cloud.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! Hand-off to Firecrawl cloud for what a laptop cannot do: web search, pages
//! that block a local fetch, and Alexandria data providers.
//!
//! Nothing here runs unless the caller asks for search or the cloud setting
//! allows a fallback. Every result says it came from the cloud and what it
//! cost, as data fields.

use std::time::Duration;

use serde_json::{json, Value};

pub const DEFAULT_API_URL: &str = "https://api.firecrawl.dev";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CloudMode {
  /// Never contact Firecrawl cloud.
  Off,
  /// Search goes to the cloud; scrapes stay local.
  SearchOnly,
  /// Search goes to the cloud, and a scrape the local engine could not
  /// complete is retried there.
  Fallback,
}

impl CloudMode {
  pub fn parse(s: &str) -> Option<CloudMode> {
    match s.trim().to_ascii_lowercase().as_str() {
      "off" | "false" | "0" | "none" | "no" | "disabled" | "disable" => Some(CloudMode::Off),
      "search" | "search-only" => Some(CloudMode::SearchOnly),
      "on" | "auto" | "fallback" | "true" | "1" | "yes" | "enabled" | "enable" => {
        Some(CloudMode::Fallback)
      }
      _ => None,
    }
  }

  /// The mode a `FIRECRAWL_CLOUD` value asks for. Unset or empty asks for
  /// nothing. A value that is not understood asks for off: someone who set
  /// it was restricting the cloud, and a typo must not open it up.
  pub fn requested(raw: Option<&str>) -> Option<CloudMode> {
    let raw = raw.map(str::trim).filter(|r| !r.is_empty())?;
    Some(CloudMode::parse(raw).unwrap_or(CloudMode::Off))
  }
}

/// Whether a path has a `.` or `..` segment, plain or percent-encoded. The
/// HTTP client resolves those before sending, so `/v2/search/../agent` would
/// arrive as `/v2/agent`. Such paths are never passed on.
pub fn has_dot_segment(path: &str) -> bool {
  path.split(['/', '\\']).any(|segment| {
    let segment = segment.to_ascii_lowercase().replace("%2e", ".");
    segment == "." || segment == ".."
  })
}

/// Say once that `FIRECRAWL_CLOUD` holds a value this build does not know.
fn warn_unknown_mode(raw: &str) {
  static ONCE: std::sync::Once = std::sync::Once::new();
  ONCE.call_once(|| {
    eprintln!(
      "FIRECRAWL_CLOUD={raw} is not a setting Firecrawl Local knows (off, search or auto). The cloud stays off."
    );
  });
}

#[derive(Clone)]
pub struct Cloud {
  client: reqwest::Client,
  base: String,
  api_key: Option<String>,
  pub mode: CloudMode,
  /// Random ID for this install, so Firecrawl can count installs, not IP
  /// addresses. Created on the first cloud call; never tied to a person.
  install_id: Option<String>,
  /// The agent harness that launched the engine (from the MCP handshake).
  harness: Option<String>,
  origin: String,
}

pub const SIGN_IN_HINT: &str = "Run `firecrawl login`, or set FIRECRAWL_API_KEY.";

fn config_dir() -> Option<std::path::PathBuf> {
  if let Some(dir) = std::env::var_os("FIRECRAWL_LOCAL_HOME") {
    return Some(std::path::PathBuf::from(dir));
  }
  std::env::var_os("HOME").map(|h| {
    std::path::PathBuf::from(h)
      .join(".config")
      .join("firecrawl-local")
  })
}

/// Where the Firecrawl CLI keeps the login from `firecrawl login`. Same
/// paths as the CLI's own `credentials.ts`.
pub fn cli_credentials_path() -> Option<std::path::PathBuf> {
  if let Some(p) = std::env::var_os("FIRECRAWL_CLI_CREDENTIALS") {
    return Some(std::path::PathBuf::from(p));
  }
  let home =
    std::path::PathBuf::from(std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?);
  let dir = if cfg!(target_os = "macos") {
    home
      .join("Library")
      .join("Application Support")
      .join("firecrawl-cli")
  } else if cfg!(target_os = "windows") {
    home.join("AppData").join("Roaming").join("firecrawl-cli")
  } else {
    home.join(".config").join("firecrawl-cli")
  };
  Some(dir.join("credentials.json"))
}

/// The API key and API URL saved by `firecrawl login`, if the user has
/// logged in with the CLI. This is what makes sign-in one step: log in once
/// in the browser and the engine picks it up.
fn cli_credentials() -> (Option<String>, Option<String>) {
  let Some(path) = cli_credentials_path() else {
    return (None, None);
  };
  let Ok(text) = std::fs::read_to_string(path) else {
    return (None, None);
  };
  let Ok(v) = serde_json::from_str::<Value>(&text) else {
    return (None, None);
  };
  let field = |name: &str| {
    v.get(name)
      .and_then(Value::as_str)
      .map(str::trim)
      .filter(|s| !s.is_empty())
      .map(str::to_string)
  };
  (field("apiKey"), field("apiUrl"))
}

/// Read this install's ID, creating it on first use.
fn load_install_id() -> Option<String> {
  let dir = config_dir()?;
  let path = dir.join("install-id");
  if let Ok(existing) = std::fs::read_to_string(&path) {
    let id = existing.trim().to_string();
    if !id.is_empty() {
      return Some(id);
    }
  }
  let id = uuid::Uuid::new_v4().to_string();
  std::fs::create_dir_all(&dir).ok()?;
  std::fs::write(&path, &id).ok()?;
  Some(id)
}

/// How the engine was started, which decides the origin its cloud calls carry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Surface {
  /// A command typed in a terminal, or run by an AI agent through one.
  Cli,
  /// The stdio MCP server.
  Mcp,
  /// The local HTTP API.
  Serve,
}

/// The origin for a surface, in the forms Firecrawl already uses:
/// `cli@<version>` for the CLI and `mcp-<client>@<version>` for an MCP
/// server, where the client is the name the MCP client gave at initialize.
/// The version is marked `local-` so Firecrawl Local can be told apart from the
/// Node CLI and the hosted MCP server.
fn origin_for(surface: Surface, client: Option<&str>) -> String {
  let version = concat!("local-", env!("CARGO_PKG_VERSION"));
  match surface {
    Surface::Cli => format!("cli@{version}"),
    Surface::Serve => format!("firecrawl-local@{version}"),
    Surface::Mcp => {
      let token: String = client
        .unwrap_or("")
        .to_ascii_lowercase()
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();
      let token: String = token
        .split('-')
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("-")
        .chars()
        .take(48)
        .collect();
      if token.is_empty() {
        format!("mcp-local@{version}")
      } else {
        format!("mcp-{token}@{version}")
      }
    }
  }
}

/// Firecrawl cloud's answer to a forwarded request, passed back untouched.
pub struct Forwarded {
  pub status: u16,
  pub content_type: Option<String>,
  pub body: bytes::Bytes,
}

#[derive(Debug)]
pub struct CloudError {
  pub status: u16,
  pub message: String,
}

impl std::fmt::Display for CloudError {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.message)
  }
}

impl Cloud {
  /// Reads `FIRECRAWL_API_KEY`, `FIRECRAWL_API_URL` and `FIRECRAWL_CLOUD`,
  /// falling back to the login saved by `firecrawl login`.
  /// With no explicit setting: a key turns the fallback on, no key means
  /// search only.
  pub fn from_env() -> Self {
    let (saved_key, saved_url) = cli_credentials();
    let api_key = std::env::var("FIRECRAWL_API_KEY")
      .ok()
      .filter(|k| !k.trim().is_empty())
      .or(saved_key);
    let base = std::env::var("FIRECRAWL_API_URL")
      .ok()
      .filter(|u| !u.trim().is_empty())
      .or(saved_url)
      .unwrap_or_else(|| DEFAULT_API_URL.to_string());
    let setting = std::env::var("FIRECRAWL_CLOUD").ok();
    if let Some(raw) = setting.as_deref().map(str::trim) {
      if !raw.is_empty() && CloudMode::parse(raw).is_none() {
        warn_unknown_mode(raw);
      }
    }
    let mode = CloudMode::requested(setting.as_deref()).unwrap_or(CloudMode::Fallback);
    Self::new(base, api_key, mode)
  }

  /// Same as `from_env`, but with the cloud off unless a key or an explicit
  /// `FIRECRAWL_CLOUD` setting turns it on. For `serve`, where the people
  /// calling the API did not install this engine themselves.
  pub fn from_env_opt_in() -> Self {
    let mut cloud = Self::from_env().with_surface(Surface::Serve, None);
    let setting = std::env::var("FIRECRAWL_CLOUD").ok();
    if CloudMode::requested(setting.as_deref()).is_none() && !cloud.has_key() {
      cloud.mode = CloudMode::Off;
    }
    cloud
  }

  /// Give the cloud a fixed install ID, so a test never writes one to the
  /// developer's config folder.
  #[cfg(test)]
  pub(crate) fn with_install_id(mut self, id: &str) -> Self {
    self.install_id = Some(id.to_string());
    self
  }

  /// Use a key obtained mid-session (after a one-step sign-in).
  pub fn with_key(mut self, api_key: String) -> Self {
    self.api_key = Some(api_key);
    self
  }

  /// Tag cloud calls with the harness that launched the engine.
  pub fn with_harness(mut self, harness: Option<String>) -> Self {
    self.harness = harness.map(|h| {
      h.chars()
        .filter(|c| c.is_ascii_graphic() || *c == ' ')
        .take(64)
        .collect()
    });
    self
  }

  pub fn new(base: String, api_key: Option<String>, mode: CloudMode) -> Self {
    let client = reqwest::Client::builder()
      .user_agent(concat!("firecrawl-local/", env!("CARGO_PKG_VERSION")))
      .connect_timeout(Duration::from_secs(10))
      .build()
      .unwrap_or_default();
    Self {
      client,
      base: base.trim_end_matches('/').to_string(),
      api_key,
      mode,
      install_id: None,
      harness: None,
      origin: origin_for(Surface::Cli, None),
    }
  }

  /// Stamp cloud calls with the surface the engine is running as, so the
  /// request is attributed the way the Firecrawl CLI and MCP server are.
  pub fn with_surface(mut self, surface: Surface, client: Option<&str>) -> Self {
    self.origin = origin_for(surface, client);
    self
  }

  pub fn origin(&self) -> &str {
    &self.origin
  }

  pub fn has_key(&self) -> bool {
    self.api_key.is_some()
  }

  /// Use the origin a client stamped on its own request, so a call the
  /// engine passes on is attributed to that client and not to the engine.
  pub fn with_origin(mut self, origin: &str) -> Self {
    let clean: String = origin
      .chars()
      .filter(|c| c.is_ascii_graphic())
      .take(100)
      .collect();
    if !clean.is_empty() {
      self.origin = clean;
    }
    self
  }

  /// Whether a request for `path` may be passed on to Firecrawl cloud.
  pub fn allows(&self, path: &str) -> bool {
    if has_dot_segment(path) {
      return false;
    }
    match self.mode {
      CloudMode::Off => false,
      CloudMode::SearchOnly => path == "/v2/search" || path.starts_with("/v2/search/"),
      CloudMode::Fallback => true,
    }
  }

  /// Pass a request this engine does not serve itself on to Firecrawl cloud
  /// and return the answer as it came. The engine's own key is used when it
  /// has one; otherwise the caller's, and with neither the call is keyless.
  pub async fn forward(
    &self,
    method: reqwest::Method,
    path_and_query: &str,
    content_type: Option<&str>,
    body: bytes::Bytes,
    client_auth: Option<&str>,
    client_origin: Option<&str>,
  ) -> Result<Forwarded, CloudError> {
    let path = path_and_query.split('?').next().unwrap_or(path_and_query);
    if !self.allows(path) {
      return Err(CloudError {
        status: 400,
        message: format!("{path} is not a path Firecrawl Local passes on to Firecrawl cloud."),
      });
    }
    let origin = match client_origin {
      Some(o) => self.clone().with_origin(o).origin,
      None => self.origin.clone(),
    };
    let mut req = self
      .client
      .request(method, format!("{}{}", self.base, path_and_query))
      .timeout(Duration::from_secs(190))
      .header("x-origin", origin)
      .body(body);
    if let Some(ct) = content_type {
      req = req.header(reqwest::header::CONTENT_TYPE, ct);
    }
    if let Some(id) = self.install_id.clone().or_else(load_install_id) {
      req = req.header("x-firecrawl-install", id);
    }
    if let Some(key) = self.api_key.as_deref().or(client_auth) {
      req = req.bearer_auth(key);
    }
    let resp = req.send().await.map_err(|e| CloudError {
      status: 502,
      message: format!("Could not reach Firecrawl cloud: {e}"),
    })?;
    let status = resp.status().as_u16();
    let content_type = resp
      .headers()
      .get(reqwest::header::CONTENT_TYPE)
      .and_then(|v| v.to_str().ok())
      .map(str::to_string);
    let body = resp.bytes().await.map_err(|e| CloudError {
      status: 502,
      message: format!("Firecrawl cloud's answer was cut short: {e}"),
    })?;
    Ok(Forwarded {
      status,
      content_type,
      body,
    })
  }

  async fn post(
    &self,
    path: &str,
    mut body: Value,
    timeout: Duration,
  ) -> Result<Value, CloudError> {
    // The scrape route reads the origin from the body only, so it travels
    // there as well as in the header.
    if let Some(obj) = body.as_object_mut() {
      obj
        .entry("origin")
        .or_insert_with(|| Value::String(self.origin.clone()));
    }
    let mut req = self
      .client
      .post(format!("{}{}", self.base, path))
      .timeout(timeout)
      .header("x-origin", &self.origin)
      .json(&body);
    if let Some(id) = self.install_id.clone().or_else(load_install_id) {
      req = req.header("x-firecrawl-install", id);
    }
    if let Some(h) = &self.harness {
      req = req.header("x-firecrawl-harness", h);
    }
    if let Some(key) = &self.api_key {
      req = req.bearer_auth(key);
    }
    let resp = req.send().await.map_err(|e| CloudError {
      status: 502,
      message: format!("Could not reach Firecrawl cloud: {e}"),
    })?;
    let status = resp.status().as_u16();
    let payload: Value = resp.json().await.unwrap_or(Value::Null);
    if !(200..300).contains(&status) {
      let detail = payload
        .get("error")
        .and_then(Value::as_str)
        .unwrap_or("request failed")
        .to_string();
      let message = match status {
        401 | 402 | 403 | 429 if !self.has_key() => {
          // The cloud sends a signup link made for this caller; pass it on.
          let link = payload
            .get("signupUrl")
            .and_then(Value::as_str)
            .map(|u| format!(" Or sign up at {u}"))
            .unwrap_or_default();
          let reason = detail.lines().next().unwrap_or("").trim();
          format!("Firecrawl cloud needs a sign-in for this ({reason}). {SIGN_IN_HINT}{link}")
        }
        401 if self.has_key() => format!(
          "Firecrawl rejected the saved login ({detail}). It may have been rotated or revoked. Run `firecrawl login` again, or update FIRECRAWL_API_KEY."
        ),
        _ => format!("Firecrawl cloud returned {status}: {detail}"),
      };
      return Err(CloudError { status, message });
    }
    Ok(payload)
  }

  /// Web search. Always a cloud call: there is no index on a laptop.
  pub async fn search(&self, query: &str, limit: u32) -> Result<Value, CloudError> {
    if self.mode == CloudMode::Off {
      return Err(CloudError {
        status: 403,
        message:
          "Web search runs on Firecrawl cloud, and the cloud is turned off (FIRECRAWL_CLOUD=off)."
            .into(),
      });
    }
    let mut payload = self
      .post(
        "/v2/search",
        json!({ "query": query, "limit": limit.clamp(1, 50) }),
        Duration::from_secs(60),
      )
      .await?;
    annotate(&mut payload);
    Ok(payload)
  }

  /// Retry a scrape in the cloud. Only called when the mode is `Fallback`.
  pub async fn scrape(&self, url: &str, options: &Value) -> Result<Value, CloudError> {
    let mut body = options.clone();
    if !body.is_object() {
      body = json!({});
    }
    body["url"] = Value::String(url.to_string());
    let mut payload = self
      .post("/v2/scrape", body, Duration::from_secs(120))
      .await?;
    annotate(&mut payload);
    Ok(payload)
  }
}

impl Cloud {
  /// Run one or more Alexandria provider calls. `calls` is one call object
  /// or an array of up to ten: `{provider, capability, options}`. Needs an
  /// account: providers cost Firecrawl money per call.
  pub async fn alexandria(&self, calls: &Value) -> Result<Value, CloudError> {
    if self.mode == CloudMode::Off {
      return Err(CloudError {
        status: 403,
        message: "Alexandria data providers run on Firecrawl cloud, and the cloud is turned off (FIRECRAWL_CLOUD=off).".into(),
      });
    }
    if !self.has_key() {
      return Err(CloudError {
        status: 401,
        message: format!("Alexandria data providers need a free Firecrawl account. {SIGN_IN_HINT} The same call works after that."),
      });
    }
    let calls = match calls {
      Value::Array(_) => calls.clone(),
      Value::Object(_) => Value::Array(vec![calls.clone()]),
      _ => return Err(CloudError {
        status: 400,
        message:
          "'alexandria' must be a call object or an array of them: {provider, capability, options}."
            .into(),
      }),
    };
    let mut payload = self
      .post(
        "/v2/scrape",
        json!({ "alexandria": calls, "origin": self.origin }),
        Duration::from_secs(190),
      )
      .await?;
    annotate(&mut payload);
    Ok(payload)
  }

  /// Browse or search the Alexandria catalogue. Tried without a key first,
  /// since browsing costs nothing; the cloud decides whether to allow it.
  pub async fn find_tools(&self, options: &Value) -> Result<Value, CloudError> {
    if self.mode == CloudMode::Off {
      return Err(CloudError {
        status: 403,
        message: "The Alexandria catalogue lives on Firecrawl cloud, and the cloud is turned off (FIRECRAWL_CLOUD=off).".into(),
      });
    }
    let call = json!([{ "provider": "firecrawl", "capability": "find-tools", "options": options }]);
    let mut payload = self
      .post(
        "/v2/scrape",
        json!({ "alexandria": call, "origin": self.origin }),
        Duration::from_secs(60),
      )
      .await?;
    annotate(&mut payload);
    Ok(payload)
  }
}

/// Scrape locally; if the page was refused and the cloud fallback is on,
/// retry it through Firecrawl. The result says where it ran.
pub async fn scrape_with_fallback(
  engine: &crate::scrape::Engine,
  cloud: &Cloud,
  url: &str,
  opts: &crate::scrape::ScrapeOptions,
) -> Result<Value, crate::scrape::ScrapeError> {
  let local = engine.scrape(url, opts).await;
  let blocked = match &local {
    Ok(doc) => {
      let status = doc
        .pointer("/metadata/statusCode")
        .and_then(Value::as_u64)
        .unwrap_or(200) as u16;
      let md = doc.get("markdown").and_then(Value::as_str).unwrap_or("");
      looks_blocked(status, md)
    }
    Err(e) => matches!(e.code, "FETCH_FAILED" | "SCRAPE_TIMEOUT"),
  };
  if blocked && cloud.mode == CloudMode::Fallback {
    let cloud_opts = json!({ "formats": ["markdown"], "onlyMainContent": opts.only_main_content });
    if let Ok(payload) = cloud.scrape(url, &cloud_opts).await {
      if let Some(mut data) = payload.get("data").cloned() {
        if let Some(obj) = data.as_object_mut() {
          obj.insert("source".into(), Value::String("firecrawl-cloud".into()));
        }
        return Ok(data);
      }
    }
  }
  match local {
    Ok(mut doc) => {
      if let Some(obj) = doc.as_object_mut() {
        obj.insert("source".into(), Value::String("local".into()));
        if blocked {
          obj.insert("blocked".into(), Value::Bool(true));
        }
      }
      Ok(doc)
    }
    Err(e) => Err(e),
  }
}

/// Mark a cloud response so callers can tell where it ran and what it cost.
fn annotate(payload: &mut Value) {
  if let Some(obj) = payload.as_object_mut() {
    obj.insert("source".into(), Value::String("firecrawl-cloud".into()));
  }
}

/// Signs that a local fetch was refused rather than served.
pub fn looks_blocked(status: u16, markdown: &str) -> bool {
  matches!(status, 401 | 403 | 407 | 429 | 503) || looks_like_bot_check(markdown)
}

/// True when a short page is a bot check or a refusal, not content.
pub fn looks_like_bot_check(markdown: &str) -> bool {
  if markdown.len() > 2000 {
    return false;
  }
  let lower = markdown.to_ascii_lowercase();
  [
    "verify you are human",
    "verifying you are human",
    "checking your browser",
    "verifying your browser",
    "quick browser check",
    "security checkpoint",
    "performing security verification",
    "enable javascript and cookies to continue",
    "attention required! | cloudflare",
    "access denied",
    "are you a robot",
    "captcha",
    "unusual traffic",
    "pardon our interruption",
  ]
  .iter()
  .any(|needle| lower.contains(needle))
}

/// A stand-in for Firecrawl cloud that returns what it was sent.
#[cfg(test)]
pub(crate) async fn echo_cloud() -> String {
  use tokio::io::{AsyncReadExt, AsyncWriteExt};
  let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
    .await
    .unwrap();
  let base = format!("http://{}", listener.local_addr().unwrap());
  tokio::spawn(async move {
    while let Ok((mut socket, _)) = listener.accept().await {
      tokio::spawn(async move {
        // Read the whole request, keeping only its first 8 KB to echo.
        let mut seen: Vec<u8> = Vec::new();
        let mut buf = vec![0u8; 64 * 1024];
        let mut wanted: Option<usize> = None;
        let mut total = 0usize;
        loop {
          let n = socket.read(&mut buf).await.unwrap_or(0);
          if n == 0 {
            break;
          }
          total += n;
          if seen.len() < 8192 {
            let room = 8192 - seen.len();
            seen.extend_from_slice(&buf[..n.min(room)]);
          }
          if wanted.is_none() {
            let text = String::from_utf8_lossy(&seen).to_lowercase();
            if let Some(head_end) = text.find("\r\n\r\n") {
              let length = text[..head_end]
                .lines()
                .find_map(|l| l.strip_prefix("content-length:"))
                .and_then(|v| v.trim().parse::<usize>().ok())
                .unwrap_or(0);
              wanted = Some(head_end + 4 + length);
            }
          }
          if wanted.is_some_and(|w| total >= w) {
            break;
          }
        }
        let request = String::from_utf8_lossy(&seen).to_string();
        let body = serde_json::json!({ "request": request }).to_string();
        let answer = format!(
          "HTTP/1.1 207 Multi-Status\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
          body.len(),
          body
        );
        let _ = socket.write_all(answer.as_bytes()).await;
      });
    }
  });
  base
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn cli_login_is_picked_up() {
    let dir = std::env::temp_dir().join(format!("fc-cred-test-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("credentials.json");
    std::fs::write(
      &path,
      r#"{"apiKey":"fc-test-key","apiUrl":"https://api.example.test"}"#,
    )
    .unwrap();
    std::env::set_var("FIRECRAWL_CLI_CREDENTIALS", &path);
    let (key, url) = cli_credentials();
    assert_eq!(key.as_deref(), Some("fc-test-key"));
    assert_eq!(url.as_deref(), Some("https://api.example.test"));
    std::fs::write(&path, "not json").unwrap();
    assert_eq!(cli_credentials(), (None, None));
    std::env::remove_var("FIRECRAWL_CLI_CREDENTIALS");
    let _ = std::fs::remove_dir_all(&dir);
  }

  #[test]
  fn origins_follow_the_cli_and_mcp_conventions() {
    let v = concat!("local-", env!("CARGO_PKG_VERSION"));
    assert_eq!(origin_for(Surface::Cli, None), format!("cli@{v}"));
    assert_eq!(
      origin_for(Surface::Serve, None),
      format!("firecrawl-local@{v}")
    );
    assert_eq!(
      origin_for(Surface::Mcp, Some("Claude Code")),
      format!("mcp-claude-code@{v}")
    );
    assert_eq!(
      origin_for(Surface::Mcp, Some("  ")),
      format!("mcp-local@{v}")
    );
    assert_eq!(origin_for(Surface::Mcp, None), format!("mcp-local@{v}"));
    assert!(origin_for(Surface::Mcp, Some("cursor/1.0 (x)")).starts_with("mcp-cursor-1-0-x@"));
  }

  #[tokio::test]
  async fn forward_passes_the_request_and_the_answer_through() {
    let base = echo_cloud().await;
    let keyless =
      Cloud::new(base.clone(), None, CloudMode::Fallback).with_install_id("test-install");
    let answer = keyless
      .forward(
        reqwest::Method::POST,
        "/v2/search?x=1",
        Some("application/json"),
        bytes::Bytes::from_static(b"{\"query\":\"q\"}"),
        None,
        Some("mcp-claude-code@3.39.0"),
      )
      .await
      .unwrap();
    assert_eq!(answer.status, 207);
    assert_eq!(answer.content_type.as_deref(), Some("application/json"));
    let seen = String::from_utf8_lossy(&answer.body).to_lowercase();
    assert!(seen.contains("post /v2/search?x=1"), "{seen}");
    assert!(seen.contains("x-origin: mcp-claude-code@3.39.0"), "{seen}");
    assert!(seen.contains("{\\\"query\\\":\\\"q\\\"}"), "{seen}");
    assert!(
      !seen.contains("authorization:"),
      "a keyless call carries no key: {seen}"
    );

    // The caller's key is used when the engine has none, and the engine's wins when it has one.
    let with_client_key = keyless
      .forward(
        reqwest::Method::GET,
        "/v2/team/credit-usage",
        None,
        bytes::Bytes::new(),
        Some("fc-client"),
        None,
      )
      .await
      .unwrap();
    assert!(String::from_utf8_lossy(&with_client_key.body).contains("Bearer fc-client"));
    let own = Cloud::new(base, Some("fc-engine".into()), CloudMode::Fallback)
      .with_install_id("test-install");
    let with_own_key = own
      .forward(
        reqwest::Method::GET,
        "/v2/team/credit-usage",
        None,
        bytes::Bytes::new(),
        Some("fc-client"),
        None,
      )
      .await
      .unwrap();
    let seen = String::from_utf8_lossy(&with_own_key.body).to_string();
    assert!(
      seen.contains("Bearer fc-engine") && !seen.contains("fc-client"),
      "{seen}"
    );
  }

  #[test]
  fn modes_decide_what_is_passed_on() {
    let cloud = |mode| Cloud::new("https://api.example.test".into(), None, mode);
    assert!(!cloud(CloudMode::Off).allows("/v2/search"));
    assert!(cloud(CloudMode::SearchOnly).allows("/v2/search"));
    assert!(cloud(CloudMode::SearchOnly).allows("/v2/search/research/papers"));
    assert!(!cloud(CloudMode::SearchOnly).allows("/v2/agent"));
    assert!(!cloud(CloudMode::SearchOnly).allows("/v2/searching"));
    assert!(cloud(CloudMode::Fallback).allows("/v2/agent"));
  }

  #[test]
  fn dot_segments_are_never_passed_on() {
    let cloud = |mode| Cloud::new("https://api.example.test".into(), None, mode);
    for path in [
      "/v2/search/../agent",
      "/v2/search/%2e%2e/agent",
      "/v2/search/%2E./agent",
      "/v2/search/./x",
      "/v2/search\\..\\agent",
      "/v2/search/..",
    ] {
      assert!(has_dot_segment(path), "{path}");
      assert!(!cloud(CloudMode::SearchOnly).allows(path), "{path}");
      assert!(!cloud(CloudMode::Fallback).allows(path), "{path}");
    }
    assert!(!has_dot_segment("/v2/search/v1.2/..hidden"));
    assert!(!has_dot_segment("/v2/search/a.b"));
  }

  #[tokio::test]
  async fn forward_refuses_a_path_it_would_not_send_as_written() {
    let cloud =
      Cloud::new(echo_cloud().await, None, CloudMode::SearchOnly).with_install_id("test-install");
    let refused = cloud
      .forward(
        reqwest::Method::POST,
        "/v2/search/../agent?x=1",
        Some("application/json"),
        bytes::Bytes::from_static(b"{}"),
        None,
        None,
      )
      .await;
    assert_eq!(refused.err().map(|e| e.status), Some(400));
  }

  #[test]
  fn a_client_origin_replaces_the_engine_origin() {
    let cloud = Cloud::new("https://api.example.test".into(), None, CloudMode::Fallback);
    assert_eq!(
      cloud.clone().with_origin("mcp-claude-code@3.39.0").origin(),
      "mcp-claude-code@3.39.0"
    );
    assert_eq!(cloud.clone().with_origin("  ").origin(), cloud.origin());
    assert_eq!(cloud.with_origin("a b\nc").origin(), "abc");
  }

  #[test]
  fn modes_parse() {
    assert_eq!(CloudMode::parse("off"), Some(CloudMode::Off));
    assert_eq!(CloudMode::parse("search"), Some(CloudMode::SearchOnly));
    assert_eq!(CloudMode::parse("auto"), Some(CloudMode::Fallback));
    assert_eq!(CloudMode::parse("nonsense"), None);
    assert_eq!(CloudMode::parse(" Disabled "), Some(CloudMode::Off));
    assert_eq!(CloudMode::parse("no"), Some(CloudMode::Off));
    assert_eq!(CloudMode::parse("yes"), Some(CloudMode::Fallback));
  }

  #[test]
  fn a_setting_that_is_not_understood_turns_the_cloud_off() {
    assert_eq!(CloudMode::requested(None), None);
    assert_eq!(CloudMode::requested(Some("  ")), None);
    assert_eq!(
      CloudMode::requested(Some("search")),
      Some(CloudMode::SearchOnly)
    );
    assert_eq!(
      CloudMode::requested(Some("auto")),
      Some(CloudMode::Fallback)
    );
    assert_eq!(CloudMode::requested(Some("offf")), Some(CloudMode::Off));
    assert_eq!(CloudMode::requested(Some("nope")), Some(CloudMode::Off));
  }

  #[test]
  fn blocked_detection() {
    assert!(looks_blocked(403, "anything"));
    assert!(looks_blocked(
      200,
      "Please verify you are human to continue"
    ));
    assert!(!looks_blocked(
      200,
      "A normal article about captcha history. "
        .repeat(100)
        .as_str()
    ));
    assert!(!looks_blocked(200, "Hello world"));
    assert!(looks_blocked(200, "We're verifying your browser\n\n[Website owner? Click here to fix](https://vercel.link/security-checkpoint)"));
    assert!(looks_blocked(
      200,
      "We're performing a quick browser check to help us fight bots."
    ));
    assert!(looks_like_bot_check("## Performing security verification"));
    assert!(!looks_like_bot_check(
      "A long guide to browser checks. ".repeat(100).as_str()
    ));
  }
}