///|
/// The system gave no random bytes.
priv suberror NoRandomBytes

///|
impl Show for NoRandomBytes with fn output(_self, logger) {
  logger.write_string("the system gives no random bytes")
}

///|
/// A new secret from the random source of the system.
fn new_secret() -> @core.Secret raise NoRandomBytes {
  guard @env.rand(32) is Some(bytes) else { raise NoRandomBytes }
  @core.Secret::of_bytes(bytes) catch {
    _ => raise NoRandomBytes
  }
}

///|
/// Who can use the server: the programs that know its secret, and the views that
/// opened a link.
priv struct Login {
  port : @core.Port
  secret : @core.Secret
  cookie : @core.CookieName
  now : () -> @app.UnixMillis
  mut links : @core.Links
  mut sessions : @core.Sessions
}

///|
/// A login with no links and no sessions.
fn Login::Login(
  instance : @app.InstanceName,
  port~ : @core.Port,
  secret~ : @core.Secret,
  now~ : () -> @app.UnixMillis,
) -> Login {
  {
    port,
    secret,
    cookie: CookieName(instance, port),
    now,
    links: @core.Links::empty(),
    sessions: @core.Sessions::empty(),
  }
}

///|
/// True when a request comes to the address of the server, and not from a page of
/// another site.
fn Login::is_same_site(self : Login, request : Request) -> Bool {
  @core.site_decision(
    self.port,
    host=(request.header)("Host"),
    origin=(request.header)("Origin"),
  )
  is SameSite
}

///|
/// True when a request has the secret of the server.
fn Login::is_program(self : Login, request : Request) -> Bool {
  (request.header)("X-Mission-Control-Secret") is Some(text) &&
  self.secret.matches(text)
}

///|
/// The kind of the view that asks for the page or its script. The cookie is enough
/// for these two only, because another local server can read it.
fn Login::page_view(self : Login, request : Request) -> @app.Surface? {
  self.sessions.find(self.cookie, (request.header)("Cookie"))
}

///|
/// True when a request has the cookie of a session, and `key` is the view key of
/// the same session.
fn Login::is_view(self : Login, request : Request, key : String?) -> Bool {
  self.sessions.find_view(
    self.cookie,
    cookie_header=(request.header)("Cookie"),
    key~,
  )
  is Some(_)
}

///|
/// The kind of the view with this key. `is_view` accepted its request before.
fn Login::surface_of(self : Login, key : String) -> @app.Surface? {
  self.sessions.surface_of(key)
}

///|
/// The view key in the header `Authorization: Bearer`. A header with another
/// scheme gives the empty text, which is no key.
fn header_key(request : Request) -> String? {
  guard (request.header)("Authorization") is Some(text) else { return None }
  match text.split_once(" ") {
    Some((scheme, key)) if scheme.to_owned().to_lower() == "bearer" =>
      Some(key.to_owned())
    _ => Some("")
  }
}

///|
/// The view key of a request for the hub. A browser cannot add a header to a
/// WebSocket, so there the key is in the query. Two different keys are no key.
fn hub_key(request : Request) -> String? {
  match (header_key(request), (request.query)("access_token")) {
    // The client sent both texts, so this comparison tells it nothing.
    (Some(header), Some(query)) if header != query => None
    (Some(key), _) | (None, Some(key)) => Some(key)
    (None, None) => None
  }
}

///|
/// The address of a new link.
fn Login::issue(
  self : Login,
  grant : @core.Grant,
) -> String raise NoRandomBytes {
  let token = new_secret()
  self.links = self.links.issue(token, grant, (self.now)())
  "\{self.port.address().to_string()}/?access_token=\{token.to_text()}"
}

///|
/// What a view gets for a link.
priv struct Entrance {
  /// The value of the header `Set-Cookie`.
  cookie : String
  key : @core.Secret
  project : @app.ProjectId?
}

///|
/// Makes a session for the token of a link, or gives `None` when no link with the
/// token works.
fn Login::redeem(self : Login, token : String) -> Entrance? raise NoRandomBytes {
  guard self.links.redeem(token, (self.now)()) is Some(grant) else {
    return None
  }
  // Two different secrets, because another local server can read the cookie.
  let cookie = new_secret()
  let key = new_secret()
  self.sessions = self.sessions.add(cookie~, key~, grant.surface)
  Some({
    cookie: @core.set_cookie(self.cookie, cookie),
    key,
    project: grant.project,
  })
}