Standard library · Network

net.ssr

Server functions, session tokens and page rendering for a front project.

import net.ssr

This package is the server side of a front project: it answers the calls a page makes to its server func functions, hands out the session tokens those calls need, and sends finished HTML for a route. It sits on net.http and net.router; Mount adds its endpoints to a router and you run the router with http.Use as usual.

A call is POST /_salam/fn/Name with Content-Type: application/json and a body like {"args":{"id":3}}. The answer is {"ok":true,"value":...} or {"ok":false,"error":"..."} with status 200 for both. The other statuses are 400 for a body that is not a JSON object, has the wrong content type or is over the size cap; 403 for a failed origin or token check; 404 for a name nobody registered; and 500 when the function answered with neither Ok nor Fail.

Calls are protected twice. The request must be same-origin: when Sec-Fetch-Site is present it must be same-origin, and when Origin is present its host must equal the Host header. There is no CORS, so a page of another site cannot read an answer. And every call needs an X-Salam-Token header, a token signed with a secret, which the page embeds or a native app fetches from GET /_salam/session. Native apps send neither Origin nor Sec-Fetch-Site, so for them the token is the whole check.

Calling a server function

The program registers one function, mounts the endpoints on a router and calls them like a browser would: it fetches a token from /_salam/session, then posts {"args":...} with the token in X-Salam-Token. The last three calls show an unknown name (404), a missing token (403) and a foreign Origin (403).

net-ssr-guide-call.salam
import net.http
import net.router
import net.ssr
import encoding.json

func add(c: i64):
    args := ssr.Args(c)
    a := json.GetInt(args, "a")
    b := json.GetInt(args, "b")
    ssr.Ok(c, "{\"sum\":" + (a + b) + "}")
end

func main:
    ssr.Register("Add", add)
    mut r := router.NewRouter()
    ssr.Mount(r)
    mut s := http.NewServer(0)
    http.Use(s, r)
    port := http.RunBackgroundPort(s)
    base := "http://127.0.0.1:" + port

    session := http.Get(base + "/_salam/session")
    token := json.Get(http.Body(session), "token")

    mut h := http.NewHeaders()
    h.Insert("Content-Type", "application/json")
    h.Insert("X-Salam-Token", token)
    good := http.PostWith(base + "/_salam/fn/Add", "{\"args\":{\"a\":2,\"b\":40}}", h)
    println http.Status(good), http.Body(good)

    unknown := http.PostWith(base + "/_salam/fn/Nope", "{\"args\":{}}", h)
    println http.Status(unknown)

    mut anon := http.NewHeaders()
    anon.Insert("Content-Type", "application/json")
    nothing := http.PostWith(base + "/_salam/fn/Add", "{\"args\":{}}", anon)
    println http.Status(nothing)

    mut cross := http.NewHeaders()
    cross.Insert("Content-Type", "application/json")
    cross.Insert("X-Salam-Token", token)
    cross.Insert("Origin", "http://evil.example")
    blocked := http.PostWith(base + "/_salam/fn/Add", "{\"args\":{}}", cross)
    println http.Status(blocked)
end
Output200 {"ok":true,"value":{"sum":42}} 404 403 403

Pages and static files

Every GET or HEAD request that is not an endpoint goes through the same fallback. A file in the folder given to SetStaticDir is sent with an ETag, and a request with a matching If-None-Match gets 304. Otherwise the function given to SetRender is called: it reads the path with PagePath and answers with Respond, for example Respond(c, 200, html, "") for a page, Respond(c, 404, html, "") for an unknown route or Respond(c, 302, "", "/login") for a redirect. Without a renderer the answer is 404.

Things that catch people out:

  • A function must answer. Call Ok or Fail before it returns, on the same thread; otherwise the caller gets a generic 500.
  • Request is per thread. It is valid in the function that was called and in the functions it calls, not in a thread you start yourself.
  • The secret. Without SetSecret or SALAM_SERVER_SECRET a new secret is made at start, so tokens from before a restart or on another instance are refused. Set it when you run more than one server.
  • Behind a proxy keep the Host header. The origin check compares it with Origin.
  • Register everything before the server starts. And mount before http.Use, because the server keeps its own copy of the router.

Types

RequestInfo

struct RequestInfo
The current request, as returned by Request.
NameTypeDescription
hi64 = 0The handle of the request context.
activebool = falseTrue when a request is being handled on this thread.
net-ssr-Mount.salam
import net.router
import net.ssr

func hello(c: i64):
    ssr.Ok(c, "{\"greeting\":\"salam\"}")
end

func page(c: i64):
    ssr.Respond(c, 200, "<h1>" + ssr.PagePath(c) + "</h1>", "")
end

func main:
    ssr.SetSecret("a-secret-with-enough-length")
    ssr.SetMaxBody(2048)
    ssr.SetTokenTtl(600)
    ssr.SetStaticDir("public")
    ssr.SetRender(page)
    ssr.Register("Hello", hello)
    known := ssr.IsRegistered("Hello")
    unknown := ssr.IsRegistered("Other")
    println known, unknown
    mut r := router.NewRouter()
    ssr.Mount(r)
    first := r.routes[0]
    println r.routes.Len(), first.method, first.pattern
    token := ssr.NewToken()
    good := ssr.CheckToken(token)
    bad := ssr.CheckToken(token + "x")
    println good, bad
    now := ssr.Request()
    inside := ssr.Valid(now)
    method := ssr.Method(now)
    println inside, method == ""
    opts := ssr.OutboundOptions()
    println opts.timeout_ms, opts.max_body, opts.max_redirects
end
Outputtrue false 2 POST /_salam/fn/:name true false false true 10000 8388608 5

Functions

Request

func Request(): RequestInfo
The request being handled on this thread: inside a server function and while a page is rendered. Outside both, active is false and every accessor answers an empty string. The strings the accessors return belong to the request and are freed when it ends; copy one to keep it.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Valid

func Valid(r: RequestInfo): bool
True when the request value belongs to a running request.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Method

func Method(r: RequestInfo): str
The HTTP method of the current request.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Path

func Path(r: RequestInfo): str
The path of the current request, without the query.

The example for this item is shown with the ones above: net-ssr-Mount.salam

func Header(r: RequestInfo, name: str): str
One request header of the current request, by name.

The example for this item is shown with the ones above: net-ssr-Mount.salam

func Cookie(r: RequestInfo, name: str): str
One cookie of the current request, by name; use it to forward a session to your backend.

The example for this item is shown with the ones above: net-ssr-Mount.salam

ClientAddr

func ClientAddr(r: RequestInfo): str
The address of the client of the current request, without the port.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Register

func Register(name: str, fn: i64)
Registers a server function under a name. The handler is a function that takes the call handle; it reads the arguments with Args and answers with Ok or Fail. Registering a name again replaces the handler. Do this before the server starts.

The example for this item is shown with the ones above: net-ssr-Mount.salam

IsRegistered

func IsRegistered(name: str): bool
True when a function is registered under the name.

The example for this item is shown with the ones above: net-ssr-Mount.salam

SetSecret

func SetSecret(secret: str)
Sets the secret that signs the session tokens. Without it the secret comes from the SALAM_SERVER_SECRET environment variable (16 bytes or more), or is generated when the server starts, which makes tokens stop working after a restart.

The example for this item is shown with the ones above: net-ssr-Mount.salam

SetMaxBody

func SetMaxBody(n: int)
Sets the largest request body, in bytes, a function call accepts. The default is 1 MiB. A bigger body is answered with 400.

The example for this item is shown with the ones above: net-ssr-Mount.salam

SetTokenTtl

func SetTokenTtl(seconds: int)
Sets how long a token stays valid, in seconds. The default is one day.

The example for this item is shown with the ones above: net-ssr-Mount.salam

SetStaticDir

func SetStaticDir(dir: str)
Sets the folder of built files, for example dist/public. A GET or HEAD request for a file in it is answered with an ETag, and If-None-Match gets 304. A directory answers with its index.html. Hidden files and paths that leave the folder are never served.

The example for this item is shown with the ones above: net-ssr-Mount.salam

SetRender

func SetRender(fn: i64)
Sets the page renderer. It is a function that takes the call handle, reads the path with PagePath and answers with Respond. Generated server code registers it; the catch-all route calls it for every GET or HEAD request that is not a file.

The example for this item is shown with the ones above: net-ssr-Mount.salam

NewToken

func NewToken(): str
Makes a signed session token. The server page embeds one, and GET /_salam/session hands one to native apps.

The example for this item is shown with the ones above: net-ssr-Mount.salam

CheckToken

func CheckToken(token: str): bool
True when the token has a good signature and is not older than the lifetime.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Args

func Args(c: i64): str
The arguments of a call: the args object of the request body, as JSON text. {} when the body had none.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Ok

func Ok(c: i64, value: str)
Answers a call with a result. The value is JSON text; the response is {"ok":true,"value":...} with status 200.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Fail

func Fail(c: i64, message: str)
Answers a call with an error text the function chose to return: {"ok":false,"error":...} with status 200. A function that answers with neither Ok nor Fail gets a generic 500.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Reject

func Reject(c: i64, status: int, message: str)
Answers a call with an error status and the message in the usual {"ok":false,"error":...} body. Use it for a bad request (400) or a refusal; Fail answers with status 200.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Respond

func Respond(c: i64, status: int, html: str, redirect: str)
Answers a page request. A non-empty redirect gives a redirect (302 unless the status is another 3xx); otherwise the status and the HTML are sent.

The example for this item is shown with the ones above: net-ssr-Mount.salam

PagePath

func PagePath(c: i64): str
The path the page renderer is asked for.

The example for this item is shown with the ones above: net-ssr-Mount.salam

Mount

func Mount(r &: router.Router)
Adds the endpoints to a router: POST /_salam/fn/:name for function calls, GET /_salam/session for tokens, and the catch-all that serves the static folder, calls the page renderer and answers 404. Call it after the routes of your own and before http.Use.

The example for this item is shown with the ones above: net-ssr-Mount.salam

OutboundOptions

func OutboundOptions(): http.RequestOptions
The defaults for calls from a server function to a backend: 10 second timeout, 8 MB response cap and up to 5 redirects.

The example for this item is shown with the ones above: net-ssr-Mount.salam

OutboundGet

func OutboundGet(url: str, headers: HashMap<str, str>): http.Response
A GET request made with OutboundOptions.

The example for this item is shown with the ones above: net-ssr-Mount.salam

OutboundPost

func OutboundPost(url: str, body: str, headers: HashMap<str, str>): http.Response
A POST request made with OutboundOptions.

The example for this item is shown with the ones above: net-ssr-Mount.salam