Security idioms in roc-chat

roc-chat is a chat server written in Roc, live at chat.lynrummy.com. In November 2026, notramo tested the live site as a black box and reported what he found. We fixed each bug. For the bigger ones, we then looked for the class each belonged to, and added a type or a check aimed at the whole class. Each section says what its type or check can't see. Some of the bugs here came from our own follow-up instead, among them a Markdown spec, an audit of what each request costs, and a sweep for decisions that let a new case through; the page says which.

Claude, an AI coding agent, wrote the fixes, the checks and this page under Steve's supervision. Every snippet is quoted from roc-chat at commit 02a5a1f, its main branch when this page was last updated, with a link to its lines; the one older snippet says so.

What the types already said

roc-chat's types already answered one question well: who is acting? A route that only the acting user may take asks for a SignedIn in its type, and a SignedIn comes from a checked session or a checked agent key. (One escape hatch checks nothing; only the first start, the demo page and tests call it.) None of the bugs below got past that.

Each bug was a question the types didn't ask. Whose credential is this call changing? What else must happen after this write? What does this request cost? What happens when a new case comes along? Each fix adds one of those questions, as a type where a type can ask it, and as a check where it can't.

What we'd ask of Roc

This is a recommendation from one project's experience. There is one so far, and this page keeps running into it.

The idea in one sketch. Roc has no linear types, so linear here is made-up syntax, and the names are simplified from roc-chat's:

# Today: this compiles, and the other devices' open streams
# outlive the sign-out. Only an outside check catches it.
sign_out_others! = |user|
    DeviceKeys.revoke_all!(user)
    Ok({})  # forgot UserStreams.end_every_stream!(user)

# With a linear type: revoking hands back a value that must
# be used exactly once, and only ending the streams uses it.
DeviceKeys.revoke_all! : UserId => linear OpenStreams
UserStreams.end_every_stream! : linear OpenStreams => {}

sign_out_others! = |user|
    streams = DeviceKeys.revoke_all!(user)
    Ok({})  # compile error: `streams` is never used

A value the compiler won't let you drop turns "you must remember to do this after that" into a type error.

roc-chat gets that one case today without linear types. A bracket with an opaque handle, shown in the streams section, makes each revoking write take a handle that only the function that ends the streams can make, so a sign-out that forgets the ending doesn't compile. Linear types would still close what the bracket can't. The bracket has to fix its body's answer type, or the body could hand the handle out, and a linear handle could leave the body and still have to be spent. And the two uses below that need "at most once" have no bracket form. Neither the bracket nor a linear type decides which writes need the handle: a new writer that forgets to take it is left for a check to catch.

Linear types

A value of a linear type must be used exactly once: it can't be copied, and it can't be dropped. An affine type is looser: at most once, so it can't be copied but may be dropped. Roc has neither. It tracks at run time whether a value is unique, to update it in place, but the type checker doesn't. Roc already goes part of the way: a statement must evaluate to {}, so a function's result can't be dropped by accident. But _ = revoke!(...) drops it on purpose and compiles.

Three places on this page would use linear types:

Nothing else, so far

The other gaps on this page are our own design choices, not Roc's. For example, the platform's answer is a plain record, so Roc's types let any module set the name its stream is held under. A check holds that today. Roc's opaque types would let us close it, by wrapping the answer in a type of the app's own, which the 31 modules that make an answer would then use. That is ours to do.

What Roc already gives us

Current Roc already does a lot for a service like this. A pure function can't do I/O, and every effect is marked by => and by the ! the compiler asks for, so a reader can see where the effects are. Only an opaque type's own module can make its values, which is what AccountProof, HumanClaim and the streams' bracket stand on. With a function that takes an effect as its argument, and that effect's answer type fixed, that is enough for a step the compiler won't let you skip. match is exhaustive, which is what RouteCost and the allow-lists below depend on, and there are no nulls.

Streams that outlived a sign-out

The bug

The devices page has a button, "Sign out other devices" (POST /devices/sign-out-others). It revoked every other device's key and advanced the session generation, so no old session cookie worked again. But a page's live updates come over an event stream, and the server judges a stream once, when it opens, then holds it for up to an hour. So a stream opened with a stolen cookie kept hearing Recent's tiles, notices and a conversation after the owner signed the other devices out. A join by an invite and a GitHub link end every session too, and they left streams open the same way. (Since the invite fix below, a join is only ever a first join, with no session to end; it still ends streams, to be safe.)

The fix: one place ends a user's streams

UserStreams is the one place the app ends a user's streams. The host does the ending; the module names whose. Its end_every_stream! ends them under each holder StreamHolder names, and it is private to the module: the bracket below is its one caller. StreamHolder is an opaque type, the one home of those names, and HttpAnswer.stream takes one and sets the answer's stream_holder from it. The platform's answer is a plain record, though, so Roc's types would let any module set stream_holder itself. The check below holds that instead.

app/StreamHolder.roc, lines 13-26

StreamHolder :: List(U8).{

	## Who holds the streams of the pages `user` opens: the user, by id.
	user : UserId -> StreamHolder
	user = |id| StreamHolder.(id.to_str().to_utf8())

	## Who holds the agent `agent`'s own stream (`AgentStream`).
	agent : UserId -> StreamHolder
	agent = |id| StreamHolder.("agent-${id.to_str()}".to_utf8())

	## The holder's name, for the host.
	to_bytes : StreamHolder -> List(U8)
	to_bytes = |StreamHolder.(bytes)| bytes
}

app/HttpAnswer.roc, lines 193-209

## An event stream the host holds open on the bus keys `keys`, 1 to 4,
## for `holder`: `backlog` first, then every frame published to any of
## `keys`. The host writes the stream's type; it is not sniffed.
stream : {
	keys : List(List(U8)),
	holder : StreamHolder,
	backlog : List(U8),
} -> Http.Response
stream = |{ keys, holder, backlog }| {
	status: 200,
	headers: [nosniff],
	body: backlog,
	kind: Stream,
	stream_keys: keys,
	stream_holder: holder.to_bytes(),
	write_grace_ms: 0,
}

The rule, held by a bracket with an opaque handle

The rule is "after this write, also do that." Every write that ends a session, revokes a credential or removes someone's access takes a UserStreams.Revoker, in place of a user id (the password's writer takes it beside its proof). Revoker is an opaque type nested in UserStreams, and only UserStreams.with_streams_ended!(id, revoke!) makes one. It hands its body, revoke!, a Revoker for id, then ends id's streams, whatever the body answered. A revoking write outside the bracket has no Revoker to pass, so it doesn't compile. Each stream then reconnects and is judged again.

streams action an action that revokes sign_out_others!, a join, a GitHub link, ... bracket UserStreams.with_streams_ended!(id, revoke!) action->bracket write revoke!'s writes each takes the Revoker bracket->write 1. a Revoker for id host the host ends every stream held under StreamHolder.user(id) and .agent(id) write->host 2. then, always, it ends outside a revoking write outside has no Revoker: no compile reconnect each stream reconnects and is judged again host->reconnect

app/UserStreams.roc, lines 22-57

UserStreams :: [].{

	## The right to make the revoking writes of one user, whose streams
	## `with_streams_ended!` ends after them. Only `with_streams_ended!`
	## makes one, and its body's answer holds none, so none outlives it.
	Revoker :: UserId.{

		## The user whose sessions, credentials or access the writes revoke.
		user : UserStreams.Revoker -> UserId
		user = |UserStreams.Revoker.(id)| id
	}

	## `revoke!` run with the right to revoke the user `id`'s sessions,
	## credentials or access, then every stream `id` holds ended: when
	## `revoke!` succeeds, and when it fails or returns early too, since a
	## write may have landed before the failure.
	with_streams_ended! : UserId,
	(UserStreams.Revoker => Try({}, [FileSystem(FileFacts.Fault)])) => Try(
		{},
		[FileSystem(FileFacts.Fault)],
	)
	with_streams_ended! = |id, revoke!| {
		revoked = revoke!(UserStreams.Revoker.(id))
		end_every_stream!(id)
		revoked
	}
}

## Every stream the user `id` holds ended now, under each holder
## `StreamHolder` names: their pages' streams (a conversation's, Recent's
## and the device code page's) and an agent's own stream.
end_every_stream! : UserId => {}
end_every_stream! = |id| {
	Host.end_every_stream_of_holder!(StreamHolder.user(id).to_bytes())
	Host.end_every_stream_of_holder!(StreamHolder.agent(id).to_bytes())
}

Three things make it hold:

Here is the sign-out, converted. The ? stops at the first failed write, and the streams are ended either way:

app/DeviceSessionsRoute.roc, lines 119-129

sign_out_others! : UserId => Try({}, [FileSystem(FileFacts.Fault)])
sign_out_others! = |id| {
	DeviceCodeFiles.revoke_or_log!(id)
	UserStreams.with_streams_ended!(
		id,
		|revoker| {
			DeviceKeyFiles.revoke_every_active_device_key!(revoker)?
			SignInFiles.advance_session_generation!(revoker)
		},
	)
}

Six actions go through the bracket: "Sign out other devices", the sign-out of a device a code signed in, a join by an invite, a GitHub link, an agent key's revoke and a member's removal from a channel. One answer changed with them: a revoking write that fails now ends the streams too, since a write may have landed before the failure. Only "Sign out other devices" did that before.

What the compiler refuses

We planted each of these in a copy of roc-chat at d275ae7, ran the pinned roc check app/main.roc, and threw the copy away. (Roc's rules of dashes are shortened here.) First, a revoking write outside the bracket, in the agent key's revoke:

── ✗ type mismatch ── app/AgentsRoute.roc:284:38

The first argument being passed to this function has the wrong type.

AgentFiles.replace_agent_key_state!(agent, revoked) ? |fault| FileSystem(fault)
                                    ^^^^^

This argument has the type:

    UserId

But the function needs the first argument to be:

    UserStreams.Revoker

Then a body that hands the Revoker out, to write with it after the bracket:

kept = UserStreams.with_streams_ended!(agent, |revoker| Ok(revoker))?
AgentFiles.replace_agent_key_state!(kept, revoked).map_err(|fault| FileSystem(fault))
── ✗ type mismatch ── app/AgentsRoute.roc:284:48

The second argument being passed to this function has the wrong type.

kept = UserStreams.with_streams_ended!(agent, |revoker| Ok(revoker))?
                                              ^^^^^^^^^

This argument has the type:

    UserStreams.Revoker -> [Err([FileSystem(FileFacts.Fault)]),
    Ok(UserStreams.Revoker)]

But the function needs the second argument to be:

    UserStreams.Revoker => Try({}, [FileSystem(FileFacts.Fault)])

With the bracket's signature made generic, (UserStreams.Revoker => Try(answer, fault)) => Try(answer, fault), the same two lines checked clean ("No errors found"). The fixed answer type is what keeps the handle inside the bracket.

Why a bracket, and not defer

This came from a question of Steve's: would Odin's defer make sense in Roc? A defer runs a step when its block ends, however it ends, but only where someone wrote it, and code that leaves it out compiles. The bracket is stronger: the first step needs a handle that only the bracket makes, and the bracket does the second step itself, so the second step can't be left out. It needs no new language feature, only an opaque type and a function that takes an effect. It is Haskell's bracket, plus opacity.

The check, narrowed to what the types can't see

The types can't say which writes revoke. That is a reader's call, and a check holds it. tools/check_stream_endings.shale reads every app module but the specs with Roc's own parser. Every function that calls one of FileFacts' writers (listed in tools/file_writers.txt, which the credential check below reads too) is judged once in tools/stream_endings.txt: ends if its write ends a session, a credential or someone's access, keeps if not, and may_end for the one writer whose value decides, a channel's members written whole. An exempt line names a function and a may_end writer it calls without removing anyone, with the reason.

tools/stream_endings.txt, lines 22-54, trimmed

ends     AccountFiles.replace_password_hash!        a new password ends every session signed over the old one
...
ends     AccountFiles.replace_session_generation!   "Sign out other devices": every session signed before admits no one
ends     AgentFiles.replace_agent_key_state!        an agent's key revoked
ends     DeviceKeyFiles.revoke_device_key!          a device's key revoked, and the session bound to it

may_end  DirectoryFiles.replace_channel_members!    a channel's members written whole: a member left out loses its conversations

keeps    AccountFiles.create_account!               a new account, which no stream holds yet
...
exempt   ChannelMembersRoute.add!  DirectoryFiles.replace_channel_members!  adding a member removes no one's access

An ends writer whose annotation takes no UserStreams.Revoker is an unguarded_writer. A call of the may_end writer from a function that takes no Revoker and has no exempt line is an unjudged_call. A member's removal goes through DirectoryFiles.replace_channel_members_without!, which takes a Revoker and crashes if its user is still in the channel. The check also holds the holders to their one home: stray_holder names any module but HttpAnswer that sets a stream_holder field. These are its findings:

tools/check_stream_endings.shale, lines 25-55

--   unjudged_writer   a function that writes a file and has no `ends`,
--                     `may_end` or `keeps` line, so a new writer is judged
--                     when it comes;
--   stale_entry       a line for no function, a verdict for a function that
--                     writes no file, or an `exempt` line for a call the
--                     function doesn't make or of no `may_end` writer;
--   unguarded_writer  an `ends` writer whose annotation takes no
--                     `UserStreams.Revoker`, so a caller could revoke
--                     without ending streams;
--   unjudged_call     a call of a `may_end` writer from a function that
--                     neither takes a `UserStreams.Revoker` nor has an
--                     `exempt` line for it;
--   stray_ending      `Host.end_every_stream_of_holder!` called anywhere but
--                     `UserStreams.end_every_stream!`;
--   unended_holder    a `StreamHolder` function that makes a holder (every
--                     one but `to_bytes`) that `UserStreams.end_every_stream!`
--                     doesn't call, so a stream held under it would outlive
--                     every revocation;
--   stray_holder      a record field `stream_holder` set in any module but
--                     `HttpAnswer`. `Http.Response` is the platform's plain
--                     record, so Roc's types let any module name a holder;
--                     `HttpAnswer.stream`, which takes a `StreamHolder`, is
--                     the one place that sets it to a holder (its `Whole`
--                     answer sets it empty), and this finding holds every
--                     other module to that, so every stream is held under
--                     a name `StreamHolder` makes.
--
-- What the check can't see: a `may_end` call it is told removes no one
-- (each `exempt` line is a reader's judgement), and a write that reaches
-- the host's files other than through FileFacts, which CLAUDE.md's rule
-- (only FileFacts touches files) keeps out.

Before the bracket, the check walked the calls from each action to the revoking writes it reached, and its unended_streams finding named an action with no ending after the write. The types hold that now, so the walk and the finding are gone; the table and the holder rules stay. The gate, tools/verify.shale, holds the check at zero, and a new writer fails it until someone judges it, so the table can't go stale. Planted faults show it sees: an ends writer taking a UserId gives unguarded_writer, a removal through the plain channel writer gives unjudged_call, and a record update that sets stream_holder in AgentStream.roc gives stray_holder.

What the bracket and the check don't catch:

A crash between the write and the ending is no gap: on a Roc crash the host panics, the server stops, and every stream ends with it.

The end-to-end tests cover the real cases: an open stream ends on "Sign out other devices", on a GitHub link, on a sign-out, on an agent key's revoke and on a member's removal.

An invite that acted as a password reset

The bug

An inviter could make a new link for a human who had already joined. Redeeming that link set whatever password the redeemer chose, and ended the joined human's own password and session. So whoever made the link could take over the account. It was broken object-level authorization: the password's writer took a bare user id, and nothing in its type said whose proof stood behind the call.

The fix: a claim, and a proof the writer demands

HumanClaim judges a human Unclaimed (no password, no GitHub link, every invite live) or Claimed. Unclaimed is opaque, and only judge makes one; judge itself is the example in the allow-lists section, below.

app/HumanClaim.roc, lines 11-42, trimmed

HumanClaim :: [].{

	## What decides it, as the human's files hold them: each invite's state
	## (`HumanInvite.State`). A damaged invite never reaches here, as its
	## read fails (`InviteFiles.read_human_invites!`), so no request judges a
	## human unclaimed without every invite of theirs read.
	Facts : {
		password : [NoPassword, HasPassword],
		github : [NotLinked, Linked],
		invites : List([Live, Spent]),
	}

	## A human with no password, no GitHub link and every invite live: the only
	## human an invite is made for, or redeems for. Only `judge` makes one.
	Unclaimed :: Users.Human.{

		## The human who has claimed nothing.
		human : HumanClaim.Unclaimed -> Users.Human
		human = |HumanClaim.Unclaimed.(unclaimed)| unclaimed
	}
...
}

Writing an invite takes an Unclaimed, so the chat writes no invite for a human who has joined. Inviting one again is a 403 saying a new link would change nothing. A join judges the link's invitee first (InviteRights.load_unclaimed_invitee!), and redeeming takes the Unclaimed that gives, so a link made before the human joined redeems nothing after. For the same reason, a joined human's live invites don't count toward their inviter's cap of 10 open invites.

app/InviteFiles.roc, lines 105-112

## A new invite in the account folder of `unclaimed`, a human who has
## claimed nothing (`HumanClaim`), made once, its hash last.
create_human_invite! : HumanClaim.Unclaimed,
HumanInvite => Try(
	{},
	[AlreadyExists, MissingDirectory, NotUtf8, PathRefused, Failed],
)
create_human_invite! = |unclaimed, invite| {

The password's one writer takes an AccountProof in place of a bare id. (A new password ends every session, so the writer also takes the UserStreams.Revoker from the streams section, and crashes if the two name different users.) Only of_first_join makes one, from an Admission, and only HumanInvite.redeem makes an Admission. Unclaimed, Redeemable, Admission and AccountProof are opaque, and an arrow that makes one is labelled with the only function that does. redeem admits the invite's own human and only requires the claim; the id check below ties the two together:

proof facts the human's files password, GitHub link, invites unclaimed HumanClaim.Unclaimed facts->unclaimed HumanClaim.judge invite create_human_invite! a new invite unclaimed->invite admission HumanInvite.Admission unclaimed->admission required redeemable HumanInvite.Redeemable the link's open invite redeemable->admission HumanInvite.redeem proof AccountProof admission->proof of_first_join writer replace_password_hash! the password's one writer proof->writer in place of a bare id

app/AccountProof.roc, lines 12-21

AccountProof :: UserId.{

	## The proof of a first join: the human an invite's redemption admitted.
	of_first_join : HumanInvite.Admission -> AccountProof
	of_first_join = |admission| AccountProof.(admission.human().id())

	## The human whose account it proves.
	human : AccountProof -> UserId
	human = |AccountProof.(id)| id
}

app/AccountFiles.roc, lines 179-195

## The password's bcrypt hash of the human whose account `proof` proves,
## written whole over the one before, atomically: a redeemed invite's
## choice, at their first join (`AccountProof`), so nothing writes one
## without the account's own proof, nor without their streams ended
## (`revoker`, whose user `proof` must prove). The hash is the host's
## (`Host.bcrypt_hash_of_password!`); the password is never kept.
replace_password_hash! : UserStreams.Revoker,
{ proof : AccountProof, hash : PasswordHash } => Try(
	{},
	[MissingDirectory, NotUtf8, PathRefused, Failed],
)
replace_password_hash! = |revoker, { proof, hash }|
	if proof.human() == revoker.user() {
		FileFacts.replace_fact!(password_path(proof.human()), hash.bytes())
	} else {
		crash "AccountFiles.replace_password_hash!: the proof and the revoker name two users"
	}

The join is the one caller. It loads the invitee as Unclaimed, redeems, and passes the proof to the writer, inside the streams' bracket:

app/HumanInvitesRoute.roc, lines 460-499, trimmed

join_by_invite! = |request| {
	...
	{ human: invited, unclaimed } = InviteRights.load_unclaimed_invitee!(request.directory, code)?
	...
	joined = HumanInvites.join(directory, { code, name, unclaimed }) ? |why| Refused(why)
	human = joined.admission.human()
	...
	hash = PasswordHash.of_bcrypt_answer(Host.bcrypt_hash_of_password!(password.bytes_to_check()))
	proof = AccountProof.of_first_join(joined.admission)
	UserStreams.with_streams_ended!(
		human.id(),
		|revoker|
			AccountFiles.replace_password_hash!(revoker, { proof, hash })
				.map_err(|fault| FileSystem(fault)),
	)?
	Ok({ admission: joined.admission, password_hash: hash, next })

To see that the types hold, we planted calls to create_human_invite! and replace_password_hash! with a bare id. roc check refused both. That shows the types differ from an id; that only their own modules can make one is what opacity adds, and stops a forged proof. What the types prove is that judge ran and that a first join made the proof. Which human a join redeems for is a runtime check: HumanInvites.join compares the Unclaimed human's id with the invite's. Once a human has joined, nothing in the app changes their password: the only AccountProof is a first join's, and there is no admin reset.

Which facts reach judge is the loader's job, read from the human's files, and the types can't see it. Our own follow-up found a gap there. The reader of a human's invites left out any invite whose files it couldn't read. Take a spent invite whose state file is garbled, for a human with no password yet (a crash between the spend and the password's write). It was left out, so the human read as unclaimed, and an invite or a join could then set their password. The reader now tells two cases apart. An invite with no hash, the file written last, was cut short before it could admit anyone, and is still left out. One with its hash and another file missing, or any file garbled so it holds no fact, fails the read as Damaged, with a line in the server's log. Every request that reads that human's invites then answers a 500 and grants nothing, until the files are mended. That includes every new invite in the chat, by anyone, since the cap on open invites reads every human's invites:

app/InviteFiles.roc, lines 66-87, trimmed

## The invites in the human `human`'s account folder, each whole. One cut
## short, with no `hash`, the file written last, was never redeemable and
## is left out. One damaged, with its `hash` but another file missing or
## any file holding no fact, fails the read (`Damaged`, logged): left
## out, it could be the spent invite that says the human joined, and an
## invite or a join would then set their password.
read_human_invites! : UserId => Try(List(HumanInvite), [Damaged, NotUtf8, PathRefused, Failed])
		...
		match read_human_invite_facts!(human_invite_folder_path(human, id)) {
			Ok(Whole(files)) =>
				match InviteFiles.human_invite_from_files(id, files) {
					Ok(invite) => {
						$invites = $invites.append(invite)
					}
					Err(BadFact(fact)) => return Err(log_damage!({ human, id, fact }))
				}
			Ok(CutShort) => {}
			Err(Missing(fact)) => return Err(log_damage!({ human, id, fact }))

The check: every path to a credential, judged

AccountProof guards one writer. The chat has more credentials than a password: GitHub links, session secrets and the session generation, device keys, device codes, agent keys and invites. tools/check_credential_writers.shale holds them all to one table, tools/credential_writers.txt. Every function that calls one of FileFacts' writers is a writes line, marked credential or other. Every call of a credential writer is a calls line naming the caller and the proof that guards it:

tools/credential_writers.txt, lines 30-59, trimmed

calls AccountFiles.replace_password_hash! HumanInvitesRoute.join_by_invite! unclaimed an AccountProof of a first join: the account's live invite code, redeemed only for a human who has claimed nothing (InviteRights.load_unclaimed_invitee!)
...
calls DeviceSessionsRoute.sign_out_others! DeviceSessionsRoute.sign_out_other_devices! own-session acting.human_in_session(): the acting human's own devices, by a full session (FullSessionRoutes)
...
calls InviteFiles.create_human_invite! HumanInvitesRoute.issue_invite! unclaimed a HumanClaim.Unclaimed, which InviteRights.load_unclaimed! makes only for a human with no password, GitHub link or spent invite, so an invite again for a joined human is refused (Joined)

A proof is one of a short list that are the account's own: own-session, own-github, own-code, unclaimed, agent-keeper, or revokes (it only ends or spends a credential). A caller that only passes the write on is marked passes-on, and its own callers are judged in turn. The gate holds three counts at zero: a writer or a call the table doesn't name, a line for code that is gone, and a proof that isn't the account's own. Before the fix the invite was that last one.

The two checks read one list of what a write is, tools/file_writers.txt. It names FileFacts' six writers, make_folder! among them: the app reads some folders' names as facts (each account is a folder), so making a folder can bring a fact into being. The stream check counted make_folder! and this one didn't, so a function that only made a folder was judged by one check and not the other. Each check still keeps its own table:

writers streams_table stream_endings.txt ends, keeps, exempt streams check_stream_endings Roc's parse tree streams_table->streams list file_writers.txt FileFacts' six writers, make_folder! among them list->streams credentials check_credential_writers regular expressions list->credentials credentials_table credential_writers.txt writes, calls, their proofs credentials_table->credentials verify tools/verify.shale each held at zero streams->verify credentials->verify

What it doesn't do: it reads lines with regular expressions, not the parse tree, so it sees a call written by its name, and not a writer passed as a value or called as a method. And it can't decide whether a proof is really the account's own; a reader decides that, once, on each line. What the check promises is that no path to a credential goes unjudged.

Smaller fixes

These three bugs weren't type questions. The first two came from notramo's testing, the third from our own Markdown spec.

A reload after a refused sign-in

A refused device code was answered at /login/code, whose GET was a bare 405. Enter in the address bar showed "POST only", and a reload of any refused sign-in posted again. Now a GET of /login/code is a 303 to /login, and the sign-in script puts its form's own GET page in the POST's place in the history (history.replaceState). The sign-in routes are one match over each path and method (sign_in_choice), and these are its lines for /login/code:

app/Route.roc, lines 431-433

(LoginCode, Get) => Open(ReturnToLogin)
(LoginCode, Post) => Open(RedeemDeviceCode)
(LoginCode, Other) => MethodNotAllowed(GetAndPost)

A doubled header

The Caddy site block in front of the chat added X-Content-Type-Options: nosniff on top of the app's own, and Mozilla's Observatory scored the doubled header invalid. The app sends it on every answer it makes, and the end-to-end tests check it on pages, scripts, images and streams. The host's own answers, its refusals (a 408, 413, 429, 431 or 503, and a 400 for a bad head) and its own 500s, carried none; our follow-up found that, and they send it too now, which the host's tests check on each. So the site block no longer adds one.

A class from a message

roc-chat's own Markdown spec found this one while testing what a message can put in the page. A form feed or a CR in a code fence's info string stayed in the language's name: ```x<FF>top-bar rendered class="language-x<FF>top-bar", which a browser reads as two classes. So a message could give its code block any class of the page's own. In roc-markdown, a fence's language now ends at any of HTML's spaces.

What a request costs

The bug

A client with no account can still make the server work. Our audit of what each request costs found that every request read the whole directory of accounts and channels from disk, twice: once to judge the request's head and once to answer it. At 300 humans a request for the favicon made 1,804 file reads. Nothing in the code said which routes may grow with the chat, so nothing caught it.

The fix: every route declares its cost

RouteCost.growth_of gives every route a cost class: Constant (the same file calls however many humans the chat has), PerReaderPlaces (a listing for each place the reader may open) or PerHuman (a read of every human's files). It is one match with no catch-all arm, so a new route fails to compile there until someone decides its class. (A new kind inside an existing route's payload, such as a new script, takes that route's class.)

app/RouteCost.roc, lines 17-89, trimmed

## Every route is written out, so a new route must declare its cost before
## it compiles. `zig build cost-check` (host/cost_check.zig) measures each
## probe of app/route_cost_probes.txt at 10 and 300 humans and holds it to
## its class, and `RouteCostSpec` holds each probe's route to the class its
## line names.
...
RouteCost :: [].{

	## How a route's file calls grow with the chat's humans: its cost class.
	Growth : [Constant, PerReaderPlaces, PerHuman]

	## The class of the route `choice`.
	growth_of : Route.Choice -> RouteCost.Growth
	growth_of = |choice|
		match choice {
			Open(ResumeOrBrowse) => Constant
			Open(ServeScript(_)) => Constant
			Open(ServeFavicon) => Constant
			Open(ServeAlertIcon) => Constant
			Open(ShowLogin) => Constant
			Open(SignIn) => Constant
			Open(SignOut) => Constant
			Open(StartGitHubSignIn) => Constant
			Open(FinishGitHubSignIn) => PerHuman
			...
			Open(RedeemDeviceCode) => PerHuman
			Open(ReturnToLogin) => Constant
			SignedInOnly(StartGitHubLink) => Constant
			SignedInOnly(ShowBrowse) => PerReaderPlaces
			SignedInOnly(ShowRecent) => PerReaderPlaces
			...
			SignedInOnly(ShowInvites) => PerHuman
			SignedInOnly(InviteHuman) => PerHuman
			SignedInOnly(InviteHumanAgain(_)) => PerHuman
			...
			SignedInOnly(SignOutOtherDevices) => Constant
			NotFound => Constant
			MethodNotAllowed(_) => Constant
		}

A declaration alone is a claim, so a probe measures it. zig build cost-check runs the real server on chats of 10 and 300 humans and counts each probe's reads, listings, writes and folder watches. A Constant probe must cost the same at both sizes, and any other must cost more at 300. So a route declared Constant that grows, or declared growing that doesn't, fails; the measure can't tell PerReaderPlaces from PerHuman. It counts file calls, not time, so a busy machine can't make it flaky.

app/route_cost_probes.txt, lines 10-31, trimmed

Constant anyone GET /favicon.ico
...
Constant anyone POST /login name=Tam&password=wrong
...
PerReaderPlaces human GET /chat
...
PerHuman human GET /invites
...
PerHuman anyone POST /login/code code=12345678

The gate runs the cost check last and holds the probes out of class at zero. The fixes that brought the routes into their classes came first: a plain read (a GET with no Authorization header) is admitted from its origin alone, and the server keeps the directory in memory, reading it again whenever its folders change. While the directory is unchanged, the favicon makes no file reads.

What it doesn't do: a route no probe reaches is declared, not measured. The counts are for a warm server with a quiet directory: the request after any change in the directory's folders reads the directory again, and a human's request that brings them online lists every other human's conversation with them, whatever its route. And a class bounds how calls grow with the number of humans, not with what one request names, such as a long transcript.

Decisions that let a new case through

The bug

Our own follow-up read every decision that says yes to some cases and no to the rest. Several named what they refused and let everything else through, by a wildcard arm, a != or a !contains. Each was right for the cases it had, but a new case, such as a new tag in a type, would have been let through without a word. HumanClaim.judge was one. It counted a human unclaimed unless an invite was Spent, so an invite state added later, an Expired say, would have counted its human as unclaimed, and an invite could then set their password.

app/HumanClaim.roc, lines 30-38, at 53fe270

## Whether `human`, whose files say `facts`, is `Unclaimed`, or has
## `Claimed` their account.
judge : Users.Human, HumanClaim.Facts -> [Unclaimed(HumanClaim.Unclaimed), Claimed]
judge = |human, { password, github, invites }|
	if password == NoPassword and github == NotLinked and !invites.contains(Spent) {
		Unclaimed(HumanClaim.Unclaimed.(human))
	} else {
		Claimed
	}

The fix: name the allowed shape once, and match the rest

The judge now matches on the password and GitHub facts. It names the one unclaimed shape once, with every invite live, and calls every other shape Claimed. is_live matches each invite state with no wildcard, so a new state stops roc check there until someone decides what it means. Planting Expired in the facts' invite states gave "Missing patterns: Expired".

app/HumanClaim.roc, lines 32-51, trimmed

	## Whether `human`, whose files say `facts`, is `Unclaimed`, or has
	## `Claimed` their account. Unclaimed is one shape, named once: no
	## password, no GitHub link, and every invite live. Any other is claimed.
	judge : Users.Human, HumanClaim.Facts -> [Unclaimed(HumanClaim.Unclaimed), Claimed]
	judge = |human, { password, github, invites }|
		match (password, github) {
			(NoPassword, NotLinked) if invites.all(is_live) =>
				Unclaimed(HumanClaim.Unclaimed.(human))
			(NoPassword, NotLinked) | (HasPassword, _) | (_, Linked) => Claimed
		}
...
## Whether an invite in `state` leaves its human unclaimed: a live one does,
## and a spent one was their join.
is_live : [Live, Spent] -> Bool
is_live = |state|
	match state {
		Live => Bool.True
		Spent => Bool.False
	}
allow_list added a new invite state Expired, say before before: !invites.contains(Spent) names what is refused added->before after after: is_live matches Live and Spent, no wildcard added->after open judged unclaimed: an invite could set the password before->open passes quietly refused roc check fails: Missing patterns: Expired after->refused someone must decide

The same sweep made the same change wherever a decision had a default:

Where a new tag could come, its commit planted one, and roc check stopped at the new match.

What it doesn't do: the compiler makes someone decide a new case, not decide it well. It can't help where the cases are bytes, not tags, as Sec-Fetch-Site's values are; there the named values are tests. And no check finds a new wildcard arm or !=; a reader does.

The lesson

The types answered "who acts?" They didn't ask "whose credential?", "what else must happen?" or "what does a request cost?" Each idiom adds one question:

In each case the rule has one home: one bracket makes the right to revoke and ends the streams, one type names their holders, one writer sets a password, one list says what a write is, each check's table judges every write, one match names every route's cost, and one arm names who is unclaimed.

The commits

In roc-chat:

In roc-markdown: c3ced12 (a fence's language ends at any HTML space).