Signed URLs
A signed URL is a link only your app could have made, for unsubscribe, email verification and download links. @signed_url() takes a route's name and parameters, as @route() does, or a path, and adds a signature. expires: makes the link stop working after that long:
<!-- routes.kscript -->
<KScript.Routes>
<import path="controllers/mail.kscript" as="mail" />
<Get path="/unsubscribe/{user}" to="mail.unsubscribe" name="unsubscribe" middleware="signed" />
</KScript.Routes>// routes.kscript
import KScript.Http
import "controllers/mail.kscript" as mail
Routes {
Get(path: "/unsubscribe/{user}", to: @mail.unsubscribe, name: 'unsubscribe', middleware: signed)
}<!-- controllers/mail.kscript -->
<import package="KScript.Http" />
<fn name="link" params="user: int" value="@signed_url('unsubscribe', user: $user, expires: 7d)" />
<fn name="unsubscribe" params="user: int">
<!-- Only a link from link() gets here: the signed middleware answers 403 to anything else. -->
<return value="@view('mail/unsubscribed', user: $user)" />
</fn>// controllers/mail.kscript
import KScript.Http
fn link(user: int) => @signed_url('unsubscribe', user: $user, expires: 7d)
fn unsubscribe(user: int) {
// Only a link from link() gets here: the signed middleware answers 403 to anything else.
return @view('mail/unsubscribed', user: $user)
}Changing any part of the path or query breaks the signature. Without the middleware, $request.has_valid_signature says whether a request's link is good. The signature is an HMAC made with a key from KSCRIPT_SECRET, so set that in production: without it, a key made at start-up is used, and links stop working when the server restarts.
Encrypting values
@encrypt() turns a value into text only your app can read, and @decrypt() gives it back. Use it for a third party's token kept in the database, or a value in a cookie. It works on text, numbers, maps and lists, and uses AES-GCM with a key made from KSCRIPT_SECRET:
<let name="stored" value="@encrypt({ access_token: 'ya29.a0', expires_in: 3600 })" />
<let name="token" value="@decrypt($stored).access_token" />$stored = @encrypt({ access_token: 'ya29.a0', expires_in: 3600 })
$token = @decrypt($stored).access_tokenText that was changed, or encrypted under another KSCRIPT_SECRET, is a Format error. Keep the secret the same across restarts and servers, or nothing encrypted before can be read.