# moonrockz/moon-lander-hubs/hosting

A SignalR hub server as a service of a Moon-Lander host, on native and on wasm
under Moonrun. The handlers and the addressing are in
[the module guide](../README.mbt.md).

## Authentication and policies

`ServerOptions` takes an authenticator. It gets the access token of the bearer
header or of the `access_token` query value, and gives an `Identity` or raises
`AuthRejected`:

```mbt check
///|
fn my_options(
  user_of_token : async (String) -> String?,
) -> @server.ServerOptions raise {
  @server.ServerOptions::new(
    @signalr.EndpointPath::parse("/chat"),
    authenticate=credentials => {
      guard credentials.token is Some(token) else {
        return @signalr.Identity::anonymous()
      }
      guard user_of_token(token.expose()) is Some(user) else {
        raise @signalr.AuthRejected("unknown token")
      }
      @signalr.Identity::user(@signalr.UserId::parse(user))
    },
    authorize=identity => !identity.has_claim("banned", "yes"),
  )
}

///|
test "the server options compile" {
  ignore(my_options(_ => None))
}
```

A refused token gives the status 401. `authorize` is the policy for every
connection; it gives 403. A method has its own policy in `on`, as `post` in
[the module guide](../README.mbt.md): a
refused call gets an error and the connection stays open.

A browser cannot set a header on a WebSocket, so the stock JavaScript client
sends the token in `access_token`. A proxy or a web server in front of the hub can
write that URL to its log. Use tokens with a short life, use TLS, and remove the
query value from the logs of the proxy. The server itself never writes a token:
its events show `/chat?id=[REDACTED]&access_token=[REDACTED]`.

## Run the hub in a host

`hub_service` binds the address in the start phase and runs the graceful drain in
the stop phase: it waits for the open calls, sends a Close message to each client
and runs the disconnect handlers. When the server cannot accept connections for a
minute, the host stops with the exit code 1. The host runs inside `with_hubs`, which owns the
tasks of the server:

```mbt check
///|
async fn run_chat(args : Array[String]) -> @lander_hosting.RunOutcome {
  @hubs_hosting.with_hubs(hubs => {
    let host = @lander_hosting.builder(
        @lander_core.AppName::parse("chat"),
        args,
      )
      |> @hubs_hosting.hub_service(
        hubs,
        "chat-hub",
        @server.BindAddress::parse("127.0.0.1:5000"),
        my_options(token => Some(token)),
        echo_hub([]),
        started=hub => println("listening \{hub.address()}"),
      )
      |> @lander_hosting.build(_ => ())
    // The command waits until a signal or a stop request cancels it.
    @lander_hosting.run(host, _ => {
      for ;; {
        @async.sleep(60000)
      }
    })
  })
}

///|
test "the host example compiles" {
  ignore(run_chat)
}
```

On native, use the console driver `moonrockz/moon-lander-hosting/console`, so that
Ctrl-C and SIGTERM give a graceful stop. On wasm, use the Moonrun driver
`moonrockz/moon-lander-hosting/moonrun`; its guide gives the limits of signals
under Moonrun. `mise run check:signalr` runs the program
`tests/signalr-hub-program` with both drivers.
