Read a line the person types at the terminal, read a password without showing it, and store a password so you can check it later.
import sys
sys.write("Your name: ")
let name = sys.readline()
print(`hello, {name}`)
$ scua --allow-tty greet.scua
Your name: Ada
hello, Ada
#Reading the terminal needs a grant
sys.readline and sys.readpassword need
--allow-tty. Without it they do not exist,
and the compiler tells you so by name rather than failing at run
time:
greet.scua:4: `sys.readline` requires the `tty` capability, which this run was not granted —
grant it with `--allow-tty` on the CLI, or the host's capability API when embedding
--allow-all and a capability file
(tty = true under [capabilities]) grant it
too.
The grant exists because the terminal is where a person types secrets. It is also never inherited by a partition: an actor cannot read the terminal even when the program that spawned it can. Read at the top level and pass the value in.
#Always guard for the end of input
Both readers return nil when there is
no more input — a closed pipe, Ctrl-D, or a run with no
terminal at all. That is not an error; it is what unattended looks
like:
let name = sys.readline()
if name == nil then
print("no input — running unattended")
else
print(`hello, {name}`)
end
Skip the guard and len(name) faults the first time
someone pipes your script into something. The same script then works in
all three shapes:
$ scua --allow-tty greet.scua # a person types
$ printf 'Ada\n' | scua --allow-tty greet.scua # piped
$ scua --allow-tty greet.scua < /dev/null # unattended
#Lines longer than 1 MiB
A line can be at most 1 MiB. A longer one is skipped: the read faults with a message saying so, and the next read returns the line after it, so a reader that catches the fault carries on with the input that followed. Nothing after the long line is lost:
while true do
match pcall(sys.readline)
Ok(line) -> do
if line == nil then break end
handle(line)
end
Error(e) -> sys.write_err("skipped a line over 1 MiB\n")
end
end
#Passwords
sys.readpassword reads a line with the terminal's echo
turned off, so the secret is not displayed and does not reach your
scrollback.
sys.write("Password: ")
let pw = sys.readpassword()
if pw == nil then
print("no password given")
else
print(`got {len(pw)} characters`)
end
Three things worth knowing.
Pasted-ahead input is discarded. If you paste
name⏎secret⏎ at the first prompt, the terminal has
already displayed the secret — it landed in the field above, which was
still echoing. No program can un-display it. What SCUA does is refuse to
use it: anything typed ahead is thrown away and you are
prompted again. Re-type at the quiet prompt.
On a pipe there is no echo to suppress, so
readpassword simply reads.
printf 'pw\n' | prog works, which is what makes scripts
testable.
The password is an ordinary string unless you ask for a secret. It lives in memory like any other value: it can be copied, printed if you print it, and saved if you save it. SCUA does not scrub it. Treat it the way you would in any language: use it, do not store it. To check it again later, store a hash of it, as the next section shows.
sys.readpassword({ as_secret = true }) returns the line
as a secret instead, which prints as
<secret>, can't be built into a string by accident,
and goes straight to crypto.argon2id_hash,
crypto.pbkdf2 or an HTTP request.
#Storing a password to check later
For accounts, a vault passphrase, or anything else where you check a
password you were given before, store
crypto.argon2id_hash(password)? and check what is typed
later with crypto.argon2id_verify. Never store the password
itself.
import crypto
-- When the account is made: keep this string, not the password.
let stored = crypto.argon2id_hash("correct horse battery staple")?
fn check(typed, stored)
match crypto.argon2id_verify(typed, stored)
Ok(ok) -> return if ok then "welcome" else "wrong password" end
Error(e) -> return `cannot use the stored hash: {e.kind}`
end
end
print(check("correct horse battery staple", stored))
print(check("Tr0ub4dor&3", stored))
print(check("anything", "$argon2id$v=19$m=4194304,t=2,p=1$c29tZXNhbHQ$CTFhFdXPJO1aFaMaO6Mm5c8y7cJHAph8ArZWb2GRPPc"))
$ scua login.scua
welcome
wrong password
cannot use the stored hash: limit
The stored string looks like
$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>.
It holds a fresh random salt and the settings it was made with, in the
standard format, so other Argon2 libraries read it and SCUA reads
theirs. argon2id_verify compares in constant time and
answers Ok(true) or Ok(false).
Argon2id is the one to use for stored passwords.
Each guess costs an attacker memory as well as time (19 MiB, two passes
by default, OWASP's recommended settings), which makes guessing on
graphics cards expensive. crypto.pbkdf2 costs only time;
keep it for formats that specify it, such as an encrypted zip, a PDF, or
an existing user table.
The stored settings are checked before they are
used. They come from your database, so a changed row could
otherwise ask for gigabytes. By default a call takes at most 64 MiB, and
at most t × m of 1,048,576 (sixteen passes over 64 MiB,
under a second on a current desktop); over either, it returns an
Error with kind limit and allocates nothing,
as in the last line above. A string that is not an Argon2id hash, or is
damaged, gives kind rejected. If you chose larger settings
yourself, raise the limits with
{ max_memory_kib = n, max_work = n }.
Changing the settings later is safe. Pass
{ t = …, m_kib = … } to argon2id_hash for new
hashes; old strings keep their own settings and still verify. To move an
old one over, hash the password again after a successful check, while
you still have it. examples/password-hash.scua
does all of this.
Three more things to know:
p(lanes) changes the result but not the speed. SCUA computes lanes one after another on the calling thread, sop = 4gives the standard answer for four lanes in the time of one.- The working memory counts against the program's memory
limit (
--max-mem, or a sandbox'smemory, 4 MiB by default). A hash that needs more than the limit leaves free gives kindlimit; in a sandbox, pass smaller settings such as{ m_kib = 1024 }or raise itsmemory. - Each call holds its partition for as long as it runs, a few tens of milliseconds at the default settings. A server checking many logins at once can run them in separate partitions.
#Don't mix
sys.readline with sys.stdin()
sys.stdin()
hands you the whole of standard input as one string. On a pipe, both
draw from the same bytes — so using both means one of them takes input
the other expected, and which one wins depends on the order you call
them.
Pick one. sys.stdin() for a payload piped in;
sys.readline for a conversation.
#The rest of the program keeps running
While sys.readline waits for a line, the rest of the
program carries on: a spawned task runs, the timers it set
with wait fire, and partitions handle their messages. A
program can show a heartbeat, poll something in the background, or serve
a partition while the person thinks:
import sys
let beats = 0
let answered = false
spawn(fn()
while not answered do
wait(250ms)
beats = beats + 1
end
end)
sys.write("Your name: ")
let name = sys.readline()
answered = true
print(`hello, {name}; {beats} heartbeats while you typed`)
$ scua --allow-tty heartbeat.scua
Your name: Ada
hello, Ada; 12 heartbeats while you typed
When nothing else has work to do, the program simply waits for the
line, using no CPU, however long the person takes. There is no time
limit on a prompt. To give up after a while, put the read inside
within:
within(30s, fn() return sys.readline() end) returns
Error with kind timeout when the time runs
out, and anything typed so far is kept for the next read.
A few reads still hold the whole program while they wait:
sys.readpassword, which keeps the terminal's echo off for exactly the time it reads.- A read under
--fast, whose clock skips through waits instead of taking them. - A read inside a function that a built-in calls for you, such as a
list.sortcomparator.
pcall(sys.readline) waits the way a plain
sys.readline() does, so catching the fault for a line over
1 MiB does not hold the program either.
Reading from inside a spawned task or a partition's
handler is refused, because there is one terminal and the top level is
the one reading it. Read at the top level and pass the line on, with
tell or through a variable the task reads.
#See also
examples/interactive.scua— the runnable version of this page- Read command-line
arguments —
sys.args, andsys.stdin()for a piped payload