Skip to main content

librojo/cli/
serve.rs

1use std::{
2    io::{self, Write},
3    net::{IpAddr, Ipv4Addr},
4    path::PathBuf,
5    sync::Arc,
6};
7
8use clap::Parser;
9use memofs::Vfs;
10use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
11
12use crate::{serve_session::ServeSession, web::LiveServer};
13
14use super::{resolve_path, GlobalOptions};
15
16const DEFAULT_BIND_ADDRESS: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
17const DEFAULT_PORT: u16 = 34872;
18
19/// Expose a Rojo project to the Rojo Studio plugin.
20#[derive(Debug, Parser)]
21pub struct ServeCommand {
22    /// Path to the project to serve. Defaults to the current directory.
23    #[clap(default_value = "")]
24    pub project: PathBuf,
25
26    /// The IP address to listen on. Defaults to `127.0.0.1`.
27    #[clap(long)]
28    pub address: Option<IpAddr>,
29
30    /// The port to listen on. Defaults to the project's preference, or `34872` if
31    /// it has none.
32    #[clap(long)]
33    pub port: Option<u16>,
34
35    /// Extra `Host`/`Origin` values the server will accept, beyond localhost and
36    /// the bind address (for example a hostname like `mypc.lan`). Repeat the
37    /// option or comma-separate to allow several. When given, this overrides the
38    /// project's `serveAllowedHosts`. Listing any host also turns on Host/Origin
39    /// validation for binds where it is otherwise off (such as `0.0.0.0`).
40    #[clap(long, value_delimiter = ',')]
41    pub allowed_hosts: Vec<String>,
42}
43
44impl ServeCommand {
45    pub fn run(self, global: GlobalOptions) -> anyhow::Result<()> {
46        let project_path = resolve_path(&self.project)?;
47
48        let vfs = Vfs::new_default()?;
49
50        let session = Arc::new(ServeSession::new(vfs, project_path)?);
51
52        let ip = self
53            .address
54            .or_else(|| session.serve_address())
55            .unwrap_or(DEFAULT_BIND_ADDRESS.into());
56
57        let port = self
58            .port
59            .or_else(|| session.project_port())
60            .unwrap_or(DEFAULT_PORT);
61
62        // The CLI flag, when given, replaces the project's list rather than
63        // merging with it, matching how --address and --port override theirs.
64        let allowed_hosts = if self.allowed_hosts.is_empty() {
65            session.serve_allowed_hosts().to_vec()
66        } else {
67            self.allowed_hosts
68        };
69
70        let server = LiveServer::new(session);
71
72        server.start((ip, port).into(), allowed_hosts, || {
73            let _ = show_start_message(ip, port, global.color.into());
74        })?;
75
76        Ok(())
77    }
78}
79
80fn show_start_message(bind_address: IpAddr, port: u16, color: ColorChoice) -> io::Result<()> {
81    let mut green = ColorSpec::new();
82    green.set_fg(Some(Color::Green)).set_bold(true);
83
84    let writer = BufferWriter::stdout(color);
85    let mut buffer = writer.buffer();
86
87    let address_string = if bind_address.is_loopback() {
88        "localhost".to_owned()
89    } else {
90        bind_address.to_string()
91    };
92
93    writeln!(&mut buffer, "Rojo server listening:")?;
94
95    write!(&mut buffer, "  Address: ")?;
96    buffer.set_color(&green)?;
97    writeln!(&mut buffer, "{}", address_string)?;
98
99    buffer.set_color(&ColorSpec::new())?;
100    write!(&mut buffer, "  Port:    ")?;
101    buffer.set_color(&green)?;
102    writeln!(&mut buffer, "{}", port)?;
103
104    writeln!(&mut buffer)?;
105
106    if !bind_address.is_loopback() {
107        let mut warning = ColorSpec::new();
108        warning.set_fg(Some(Color::Yellow)).set_bold(true);
109
110        buffer.set_color(&warning)?;
111        writeln!(
112            &mut buffer,
113            "WARNING: This server is bound to {address_string}, which is reachable from the \
114             network.\n\
115             The serve API is unauthenticated, so anyone who can reach {address_string}:{port} \
116             can read\n\
117             and modify your project's source. Prefer binding to localhost and tunneling (e.g. \
118             SSH,\n\
119             Tailscale, or WireGuard) when you need remote access."
120        )?;
121        buffer.set_color(&ColorSpec::new())?;
122        writeln!(&mut buffer)?;
123    }
124
125    buffer.set_color(&ColorSpec::new())?;
126    write!(&mut buffer, "Visit ")?;
127
128    buffer.set_color(&green)?;
129    write!(&mut buffer, "http://{}:{}/", address_string, port)?;
130
131    buffer.set_color(&ColorSpec::new())?;
132    writeln!(&mut buffer, " in your browser for more information.")?;
133
134    writer.print(&buffer)?;
135
136    Ok(())
137}