KScript docs
EN

KScript.Auth

Sign-in for kscript serve apps: users, sessions, the auth and guest middleware, CSRF, password resets and API tokens.

Import it at the top of a script:

<import package="KScript.Auth" />
import KScript.Auth

KScript.Auth signs people in to a kscript serve app, so its examples can't run inside the docs. Copy one into a .ks.xml file and run it with kscript.

ElementsStatements

#<policy>policy

Says who may do what to a model's records. Each <fn> inside is an ability, named for what it allows (create, read, update, delete, or your own), that takes the user and then the record and returns true or false: policy for Post { fn update(user: User, post: Post) => $user.id == $post.author_id }. A user typed User? lets a guest reach the function with null; any other type turns a guest away first. fn before(user) runs ahead of every ability: true or false decides, null carries on. Keep one policy per model, in the project's policies folder, where @can finds it by the model's name.Says who may do what to a model's records. Each fn inside is an ability, named for what it allows (create, read, update, delete, or your own), that takes the user and then the record and returns true or false: policy for Post { fn update(user: User, post: Post) => $user.id == $post.author_id }. A user typed User? lets a guest reach the function with null; any other type turns a guest away first. fn before(user) runs ahead of every ability: true or false decides, null carries on. Keep one policy per model, in the project's policies folder, where @can finds it by the model's name.
Says who may do what to a model's records. Write policy for Post { fn update(user: User, post: Post) => $user.id == $post.author_id }.

Holds statements.Holds statements in { }. Scripts only.

AttributeValueDescription
for requireda stringThe model, or type, the policy is for.
descriptiona stringWhat the policy is for, shown on hover.
Example
<import package="KScript.Data" /><model name="Note"><field name="owner_id" type="int" /></model>
<policy for="Note">
  <fn name="read" params="user, note: Note" value="$user != null and $user.id == $note.owner_id" />
</policy>
import KScript.Data
model Note {
  owner_id: int
}
policy for Note {
  fn read(user, note: Note) => $user != null and $user.id == $note.owner_id
}

Commands

Commands are called with @, in any expression: @name(arguments).

#@acting_as(user) → any

In a test, sets who @can, @authorize and @user() ask about until the test ends, in the test and in routes it calls with @api(/...): @acting_as($editor). Pass null to act as a guest.
Example
<do>@acting_as({ id: 1, role: 'editor' })</do>
@acting_as({ id: 1, role: 'editor' })

#@acting_as_guest(id?: any) → any

In a test, acts as a guest until the test ends, in the test and in routes it calls with @api(/...) or @visit(): @guest() is this id (a new one when it is left out), and no one is signed in until a request sends the session cookie of someone who signed in, as a browser would after sign-in. Returns the guest id.
ParameterTakes
id optionalany
Example
<do>@acting_as_guest()</do>
@acting_as_guest()

#@api_token(user, name?, expires?: duration) → string

Makes an API token for a user and returns it. Show it once: only its hash is kept. Requests that send it as Authorization: Bearer <token> are signed in as the user (the auth middleware lets them through). expires is how long it works for, such as 30d; by default it lasts until it is revoked.
ParameterTakes
user requiredany value
name optionalany value
expires optionalduration

Arguments can be named: @api_token(…, name: …, expires: …).

Example
<let name="token" value="@api_token(@user(), name: 'laptop')" />
$token = @api_token(@user(), name: 'laptop')

#@api_tokens(user) → list

A user's API tokens, without the tokens themselves: [{ id, name, created_at, last_used_at, expires_at }].
Example
<for each="t" in="@api_tokens(@user())"><echo>{ $t.name }</echo></for>
for t in @api_tokens(@user()) {
  echo $t.name
}

#@attempt(email, password, remember?: bool, session?: bool) → map

Signs someone in with an email and password: returns the user, or null when they don't match. session: false only checks them, for an API that answers with a token instead of a cookie. After http.auth.attempts (5) failures for the same email and address in http.auth.lockout (a minute), it throws a TooManyRequests error that says how long to wait (kscript serve answers it with 429).
ParameterTakes
email requiredany value
password requiredany value
remember optionala flag: remember or not remember
session optionala flag: session or not session

Arguments can be named: @attempt(…, password: …, remember: …).

Example
<let name="user" value="@attempt($form.email, $form.password, remember: $form.remember)" />
$user = @attempt($form.email, $form.password, remember: $form.remember)

#@authorize(ability, target) → any

Stops unless the model's policy lets the user use the ability: a Forbidden error (403 in a route), or Unauthorized (401, or the sign-in page) for a guest the ability turns away. Returns the target, so it can be chained.

Arguments can be named: @authorize(…, target: …).

Example
<do>@authorize(update, $post)</do>
@authorize(update, $post)

#@can(ability, target) → bool

True when the model's policy lets the user use the ability on a record: @can(update, $post). For an ability with no record yet, name the model: @can(create, Post). The user is the signed-in one, or null for a guest.

Arguments can be named: @can(…, target: …).

Example
<if test="@can(update, $post)"><echo>Edit</echo></if>
if @can(update, $post) {
  echo 'Edit'
}

#@cannot(ability, target) → bool

The opposite of @can: true when the policy doesn't let the user use the ability.

Arguments can be named: @cannot(…, target: …).

Example
<if test="@cannot(update, $post)"><echo>Read only</echo></if>
if @cannot(update, $post) {
  echo 'Read only'
}

#@csrf_field() → string

A hidden form field holding the CSRF token: write {! @csrf_field() } inside each <form method="post">.
Example
<form method="post" action="/login">{! @csrf_field() }</form>
form(method: 'post', action: '/login') "{! @csrf_field() }"

#@csrf_token() → string

The session's CSRF token. Forms send it back as _token, and scripts as an X-CSRF-Token header.
Example
<meta name="csrf-token" content="{ @csrf_token() }" />
meta(name: 'csrf-token', content: @csrf_token())

#@file_users() → list

The users kept as files in the app's data folder, as before http.auth.users kept them in a model: each with its id, password_hash and its created_at and updated_at as dates. For a migration's Run block that copies them into the User model with the ids they had.
Example
<echo>{ @file_users()->count() } people signed up before the users moved into a model</echo>
echo "{ @file_users()->count() } people signed up before the users moved into a model"

#@guest() → any

The browser's guest id: the key of its Guest (a uuid, unless your copy of Guest says otherwise), kept in a long-lived cookie (http.auth.guest_lifetime, a year by default) and made the first time it is read. Null once someone is signed in, and outside a request. Ownable records a guest makes belong to it.
Example
<echo>{ @guest() }</echo>
echo @guest()

#@has_passkeys() → bool

True when this site has a configured passkey origin.
Example
<if test="@has_passkeys()"><button type="button" passkey="login">Sign in with a passkey</button></if>
if @has_passkeys() {
  button(type: 'button', passkey: 'login') "Sign in with a passkey"
}

#@intended(default?) → string

Where to go after signing in: the page the auth middleware sent someone away from, else default (http.auth.home, /). It is always a path on this site.
Example
<return value="@redirect(@intended())" />
return @redirect(@intended())

#@is_confirmed(within?: duration) → bool

True when the signed-in user signed in or checked their passkey within this long (http.auth.confirm_within, or 5 minutes, by default). Ask for a passkey check before something that can't be undone, such as deleting the account.
ParameterTakes
within optionalduration
Example
<if test="!@is_confirmed()"><button type="button" passkey="login">Confirm it's you</button></if>
if !@is_confirmed() {
  button(type: 'button', passkey: 'login') "Confirm it's you"
}

#@is_signed_in() → bool

True when someone is signed in (by the session or an API token).
Example
<if test="@is_signed_in()"><echo>Welcome back</echo></if>
if @is_signed_in() {
  echo 'Welcome back'
}

#@login(user, remember?: bool) → map

Signs a user in: the session gets a new id and the user. remember keeps them signed in for http.auth.remember (30 days) after the browser closes. The user is a map with an id: from @register(), @users()->find(), or a store of your own.
ParameterTakes
user requiredany value
remember optionala flag: remember or not remember

Arguments can be named: @login(…, remember: …).

Example
<do>@login($user, remember: true)</do>
@login($user, remember: true)

#@logout(everywhere?: bool)

Signs out: the session ends and its cookie is removed. everywhere ends the user's sessions on every device.
ParameterTakes
everywhere optionala flag: everywhere or not everywhere
Example
<do>@logout()</do>
@logout()

#@oidc_abort(uid) → string

Ends a sign-in step without signing in: the app is told access_denied. Gives the address to send the browser to next, or null.
Example
<let name="next" value="@oidc_abort($params.uid)" />
$next = @oidc_abort($params.uid)

#@oidc_account_deleted(user) → number

Call as a user's account is deleted: their app grants go, and each app with an account_deletion_uri is sent a signed account-purged notice, retried until it answers. Gives how many notices were queued.
Example
<do>@oidc_account_deleted($user)</do>
@oidc_account_deleted($user)

#@oidc_connections() → list

The apps the signed-in user has let sign them in, newest first: client_id, client_name, scopes, granted_at and last_used_at (seconds since 1970).
Example
<for each="app" in="@oidc_connections()"><echo>{ $app.client_name }</echo></for>
for app in @oidc_connections() {
  echo $app.client_name
}

#@oidc_consent(uid, allow: bool) → string

Answers a consent step: allow lets the app see what it asked for, from now on; otherwise the app is told access_denied. Gives the address to send the browser to next, or null when the step isn't this browser's.
ParameterTakes
uid requiredany value
allow requireda flag: allow or not allow

Arguments can be named: @oidc_consent(…, allow: …).

Example
<let name="next" value="@oidc_consent($params.uid, allow: $form.decision == 'allow')" />
$next = @oidc_consent($params.uid, allow: $form.decision == 'allow')

#@oidc_data_exports(user) → list

Asks each app with a data_export_uri for a copy of what it holds about the user, all at once, for their data download: one map per app with client_id, client_name, included (false when the app couldn't be asked within 30 seconds or didn't answer with a JSON object) and data, the object it answered with.
Example
<let name="apps" value="@oidc_data_exports(@user())" />
$apps = @oidc_data_exports(@user())

#@oidc_disconnect(client_id) → bool

Takes an app's access away from the signed-in user: the app's tokens stop working at once, and it asks again next time. True when it had access.
Example
<do>@oidc_disconnect($form.client_id)</do>
@oidc_disconnect($form.client_id)

#@oidc_interaction(uid) → map

The sign-in step an app sent this browser to (http.auth.provider), for the page at {interaction}/{uid}: uid, prompt (login or consent), client_id, client_name, return_host, scopes, ui_locales, login_hint and resume, the address to send the browser to once the step is done. Null unless this browser started it and it hasn't run out.
Example
<let name="sign_in" value="@oidc_interaction($params.uid)" />
$sign_in = @oidc_interaction($params.uid)

#@oidc_subscriptions(user, blocking_only?: bool) → list

Asks each app with a subscriptions_uri which subscriptions the user has there, all at once, before their account is deleted: one map per app with client_id, client_name, blocking, checked (false when the app couldn't be asked), subscriptions (name, store, renews, ends_at, manage_url) and blocks (it has block_deletion_with_subscriptions and one still renews). blocking_only asks only those apps.
ParameterTakes
user requiredany value
blocking_only optionala flag: blocking_only or not blocking_only

Arguments can be named: @oidc_subscriptions(…, blocking_only: …).

Example
<let name="held" value="@oidc_subscriptions(@user(), blocking_only: true)->filter(fn(app) => $app.blocks)" />
$held = @oidc_subscriptions(@user(), blocking_only: true)->filter(fn(app) => $app.blocks)

#@passkey(action, step, body) → map

Runs one step of a passkey ceremony from one of the app's own POST routes, as /_ks/passkeys/{action}/{step} does: action is login, register or signup, step is options or verify, and body is the JSON the browser sent. Gives the answer for the browser as a map. A failed check throws (Forbidden, Validation or Unauthorized).

Arguments can be named: @passkey(…, step: …, body: …).

Example
<let name="options" value="@passkey('login', 'options', $request.body)" />
$options = @passkey('login', 'options', $request.body)

#@passkeys() → list

Lists the signed-in session user's passkeys for this site: each one's id, created_at, last_used_at (null until it signs in) and synced (true for a passkey that is backed up, such as one in a password manager).
Example
<for each="key" in="@passkeys()"><echo>{ $key.created_at }</echo></for>
for key in @passkeys() {
  echo $key.created_at
}

#@register(email, password, fields...: User) → map

Adds a user and returns it (without signing them in). The email and password are checked by the email and password types, with your project's rules ("types": { "password": { "min": 12 } } in kscript.json); a problem, or an email that is taken, is a Validation error naming the field. The password is kept only as an argon2id hash. Other named values are kept as the user's fields.
ParameterTakes
email requiredany value
password requiredany value
fieldsUser, any number of them

Arguments can be named: @register(…, password: …, fields: …).

Example
<let name="user" value="@register($form.email, $form.password, name: $form.name)" />
$user = @register($form.email, $form.password, name: $form.name)

#@reset_password(token, password) → map

Finishes a password reset: gives the token's user the new password (checked by the password type) and ends their sessions. Returns the user, or null when the token is wrong, used or too old.

Arguments can be named: @reset_password(…, password: …).

Example
<let name="user" value="@reset_password($form.token, $form.password)" />
$user = @reset_password($form.token, $form.password)

#@reset_token(email) → string

Starts a password reset: a token to put in a link you email to the person, or null when no user has that email. It works once, for http.auth.reset_lifetime (an hour), and a new one replaces the last. Tell the person the same thing either way, so the page doesn't show who has an account.
Example
<let name="token" value="@reset_token($form.email)" />
$token = @reset_token($form.email)

#@revoke_passkey(id) → bool

Revokes one of the signed-in session user's passkeys by its id. True when it was removed.
Example
<do>@revoke_passkey($id)</do>
@revoke_passkey($id)

#@revoke_token(token, user?) → bool

Revokes an API token, given as the token or its id (from @api_tokens()). With user, only a token of theirs is revoked, so a page can let people revoke their own. True if there was one.

Arguments can be named: @revoke_token(…, user: …).

Example
<do>@revoke_token($id)</do>
@revoke_token($id)

#@user() → map

The signed-in user (a map with id, email and the fields they registered with), or null for a guest. It comes from the session cookie, or from an API token (Authorization: Bearer).
Example
<if test="@user() != null"><echo>Hello { @user().email }</echo></if>
if @user() != null {
  echo "Hello { @user().email }"
}

#@users() → users

The app's users, kept in its data folder: ->find(id), ->find_email(email), ->all(), ->count(), ->verify(email, password), ->update(id, ...), ->set_password(id, password), ->delete(id).
Example
<echo>{ @users()->count() } people have signed up</echo>
echo "{ @users()->count() } people have signed up"

#@verification_token(user, expires?: duration) → string

A token that proves a user owns their email address, to put in the link of a verify-your-email message: @route('verification.verify', token: @verification_token($user)). It is signed with the app's secret (KSCRIPT_SECRET), names the user and their email, and works until expires (an hour by default), or until their email changes. Nothing is kept: @verify_email() checks it.
ParameterTakes
user requiredany value
expires optionalduration

Arguments can be named: @verification_token(…, expires: …).

Example
<let name="token" value="@verification_token(@user(), expires: 24h)" />
$token = @verification_token(@user(), expires: 24h)

#@verify_email(token) → map

Finishes email verification: sets the token's user's email_verified_at to now and returns the user, or null when the token is wrong, has run out, or was made for an email the user no longer has. A user who is already verified keeps the time they were first verified. The verified middleware lets only verified users through.
Example
<let name="user" value="@verify_email($token)" />
$user = @verify_email($token)

Methods

On session values: ->get(), ->has(), ->set(), ->flash(), ->remove(), ->pull(), ->clear(), ->all(), ->regenerate()

On users values: ->find(), ->find_email(), ->all(), ->count(), ->verify(), ->update(), ->set_password(), ->delete()

Variables

VariableTypeDescription
$sessionsessionThe request's session: values kept between requests by a cookie. $session->set('cart', $items), $session->get('cart'), and $session->flash('status', 'Saved') for a message after a redirect.

Models and mixins

KScript.Auth ships these, written in KScript:

  • User, a model: Someone with an account. KScript.Auth keeps the users in this model when kscript.json says "http": { "auth": { "users": "User" } }: @register makes one, and @user() is the one…
  • Guest, a model: Someone using the app without an account. Each browser gets one, kept in a long-lived cookie, and it is stored the first time it owns a record. Its key is what @guest() gives. It…
  • Ownable, a mixin: Rows that belong to one owner: the signed-in user, or the browser's guest. A model that extends Ownable gets a user and a guest, one of them filled in from who is making a record…

Every option a model takes and every built-in mixin: Models and mixins.