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).
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)
endPages 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
OkorFailbefore it returns, on the same thread; otherwise the caller gets a generic 500. Requestis 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
SetSecretorSALAM_SERVER_SECRETa 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
Hostheader. The origin check compares it withOrigin. - Register everything before the server starts. And mount before
http.Use, because the server keeps its own copy of the router.
Types
RequestInfo
struct RequestInfoRequest.| Name | Type | Description |
|---|---|---|
h | i64 = 0 | The handle of the request context. |
active | bool = false | True when a request is being handled on this thread. |
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
endFunctions
Request
func Request(): RequestInfoactive 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): boolThe example for this item is shown with the ones above: net-ssr-Mount.salam
Method
func Method(r: RequestInfo): strThe example for this item is shown with the ones above: net-ssr-Mount.salam
Path
func Path(r: RequestInfo): strThe example for this item is shown with the ones above: net-ssr-Mount.salam
Header
func Header(r: RequestInfo, name: str): strThe example for this item is shown with the ones above: net-ssr-Mount.salam
Cookie
func Cookie(r: RequestInfo, name: str): strThe example for this item is shown with the ones above: net-ssr-Mount.salam
ClientAddr
func ClientAddr(r: RequestInfo): strThe example for this item is shown with the ones above: net-ssr-Mount.salam
Register
func Register(name: str, fn: i64)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): boolThe example for this item is shown with the ones above: net-ssr-Mount.salam
SetSecret
func SetSecret(secret: str)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)The example for this item is shown with the ones above: net-ssr-Mount.salam
SetTokenTtl
func SetTokenTtl(seconds: int)The example for this item is shown with the ones above: net-ssr-Mount.salam
SetStaticDir
func SetStaticDir(dir: str)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)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(): strGET /_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): boolThe example for this item is shown with the ones above: net-ssr-Mount.salam
Args
func Args(c: i64): strargs 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){"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){"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){"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)The example for this item is shown with the ones above: net-ssr-Mount.salam
PagePath
func PagePath(c: i64): strThe example for this item is shown with the ones above: net-ssr-Mount.salam
Mount
func Mount(r &: router.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.RequestOptionsThe example for this item is shown with the ones above: net-ssr-Mount.salam
OutboundGet
func OutboundGet(url: str, headers: HashMap<str, str>): http.ResponseOutboundOptions.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.ResponseOutboundOptions.The example for this item is shown with the ones above: net-ssr-Mount.salam