Auth middleware and a CurrentUser service

By Esteban Trillo4 min readupdated Effect on the BackendEffectTypeScript

Users.create has a CurrentUser-shaped slot. Only the Authorization middleware carries the piece that fits, and without it the code doesn't compile.
Users.create has a CurrentUser-shaped slot. Only the Authorization middleware carries the piece that fits, and without it the code doesn't compile.

Part 11 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the part-11 tag.

Part 10 ended with anyone able to create a user and nothing recording who did it. This part fixes both. POST /users needs a bearer token now, and the created event gets an actor_id.

The usual Node answer is a middleware that sets req.user. With Passport, @types/passport declares it as user?: User | undefined on every Express request, because the type can’t know whether the middleware ran on this route. Every handler then writes req.user! or checks again. I wanted the opposite: code that needs a user says so in its type, and a route that doesn’t authenticate can’t call it.

Tokens, stored hashed

Tokens live in Postgres, in a new migration:

src/migrations/0003_create_api_tokens.ts (excerpt)
CREATE TABLE api_tokens (
token_hash text PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE user_events ADD COLUMN actor_id bigint REFERENCES users (id)

A Tokens service issues them and checks them. A token is 32 random bytes from node:crypto, and the table only ever sees its SHA-256. If the table leaks, nobody can log in with what’s in it. These are random tokens rather than passwords, so a fast hash is enough; bcrypt is for secrets a human picked.

src/Tokens.ts (excerpt)
verify: Effect.fn("Tokens.verify")(
function* (token: Redacted.Redacted) {
return yield* findByHash(hash(Redacted.value(token))).pipe(
Effect.catchTag("NoSuchElementError", () => new Unauthorized()),
)
},
Effect.catchTags({ SqlError: Effect.die, SchemaError: Effect.die }),
),

It’s part 9’s SqlSchema.findOne again, joining api_tokens to users and decoding the row with User. A missing row means a bad token. To get one, npm run -s token -- 1 prints a new token for Ada, once.

The contract half

The middleware has two halves, like the API in part 5. The declaration goes in a module the client can import:

src/Auth.ts
// The user behind the bearer token. Only the Authorization middleware provides it.
export class CurrentUser extends Context.Service<CurrentUser, User>()("CurrentUser") {}
export class Unauthorized extends Schema.TaggedError<Unauthorized>()(
"Unauthorized",
{},
{ httpApiStatus: 401 },
) {}
export class Authorization extends HttpApiMiddleware.Service<Authorization, {
provides: CurrentUser
}>()("Authorization", {
security: { bearer: HttpApiSecurity.bearer },
error: Unauthorized,
}) {}

CurrentUser is an ordinary service whose value is a User. Authorization says three things: it reads a bearer token, it provides CurrentUser, and it can fail with Unauthorized, which is a 401 the same way part 6’s UserNotFound is a 404. HttpApiSecurity.bearer also lands in the OpenAPI spec as a bearer security scheme, and POST /users lists 401 next to its 201 and 400.

Then the endpoint opts in:

src/Api.ts (excerpt)
// Creating a user needs a bearer token. get stays public.
HttpApiEndpoint.post("create", "/users", {
payload: NewUser,
success: User.pipe(HttpApiSchema.status(201)),
}).middleware(Authorization),

get stays public. .middleware() works on a group or the whole API too, as part 6 did with Validation.

The implementation half

src/main.ts (excerpt)
// Look the token up, then run the endpoint with its user provided as CurrentUser.
const AuthorizationLive = Layer.effect(
Authorization,
Effect.gen(function* () {
const tokens = yield* Tokens
return Authorization.of({
bearer: Effect.fn("Authorization.bearer")(function* (httpEffect, { credential }) {
const user = yield* tokens.verify(credential)
return yield* Effect.provideService(httpEffect, CurrentUser, user)
}),
})
}),
).pipe(Layer.provide(Tokens.layer))

The bearer key matches the key in security. Effect parses the Authorization header and hands over the token as a Redacted, so it prints as <redacted> in logs, like part 7’s database URL. httpEffect is the rest of the request: the payload decoding and the handler. The middleware runs it with CurrentUser provided, and if verify fails, it never runs.

AuthorizationLive goes next to ValidationLive in the group’s Layer.provide. Tokens.layer needs SqlClient, which part 9 already provides once, outside serve. main.ts is 61 non-blank lines (part 10: 46).

Asking for the user

Here’s the line the whole part is for. Users.create yields CurrentUser itself:

src/Users.ts (excerpt)
function* (input: NewUser) {
// Yielding CurrentUser puts it in create's type: only a caller that has a user can run it.
const actor = yield* CurrentUser
const user = yield* insert(input)
yield* sql`INSERT INTO user_events ${sql.insert({ user_id: user.id, type: "created", actor_id: actor.id })}`

create now returns Effect<User, never, CurrentUser>. The handler didn’t change at all; it’s still users.create(payload), and it compiles because the endpoint’s middleware provides CurrentUser. I deleted .middleware(Authorization) from the endpoint to check, in src/part-11/types.ts:

npm run check (src/part-11/types.ts without its @ts-expect-error, trimmed)
error TS2375: Type 'Layer<Service<"open", "users">, never, Request<"Requires", CurrentUser>>' is not assignable to type 'Layer<Service<"open", "users">, never, never>'
Type 'Request<"Requires", CurrentUser>' is not assignable to type 'never'.

That’s the same per-request requirement part 8 ran into with Users. Make the same deletion in the real Api.ts and main.ts fails on its last line, with CurrentUser left in the requirements of the effect runMain gets. The same thing happens outside HTTP. A script that creates a user gets CurrentUser | Users in its requirements and has to provide someone, which is what the part 8 side files now do with Ada.

A middleware that checks the token and forgets to provide the user doesn’t compile either: Type 'CurrentUser' is not assignable to type 'Provided'.

You delete .middleware(Authorization) from the create endpoint. The handler still calls users.create(payload), and Users.create yields CurrentUser. What happens?

What curl sees

curl against npm start
POST /users, no header 401 {"_tag":"Unauthorized"}
POST /users, Bearer nope 401 {"_tag":"Unauthorized"}
POST /users, Basic <token> 401 {"_tag":"Unauthorized"}
POST /users, Bearer <token> 201 {"id":"2","name":"Grace","email":"grace@example.com"}
POST /users, bearer <token> 201 {"id":"3","name":"Linus","email":"linus@example.com"}
GET /users/2, Bearer nope 200 {"id":"2","name":"Grace","email":"grace@example.com"}

Both new events have actor_id 1, Ada. The lowercase bearer works because HTTP auth schemes are case-insensitive, and Effect’s parser follows RFC 9110 there. GET ignores the bad token because nothing on that endpoint reads it.

The client sends the token on every request with transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(token)), reading TOKEN with Config.Redacted. Run it with TOKEN=nope and it fails with the rebuilt Unauthorized class. Its type knows that too: catchTag("Unauthorized") compiles on create and fails on get.

Gotchas

  • 401 beats 400. An unauthenticated POST with a blank name gets a 401, not part 6’s BadRequest. Payload decoding happens inside httpEffect, and the middleware never runs it. Same for broken JSON. I think that’s right: a stranger shouldn’t learn your validation rules.
  • A missing header isn’t a decode failure. Effect reads a missing or malformed Authorization header as an empty Redacted and calls your middleware anyway.1 Mine hashes the empty string and finds nothing, which costs one query. If yours checks a signature instead, make sure "" fails.
  • No WWW-Authenticate header. RFC 6750 asks for one on a bearer 401. Effect 4.0.5 doesn’t add it, and curl and the Effect client didn’t care, so I left it out.
  • Tokens never expire. Revoking one means deleting its row. An expires_at column is a one-line migration when something needs it.
POST /users with no Authorization header and the body {"name":""}. What comes back?

Run it

Terminal window
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-11
npm install
docker compose up -d --wait
cp .env.example .env
npm start

In another terminal:

Terminal window
TOKEN=$(npm run -s token -- 1)
curl -X POST localhost:3000/users -H "authorization: Bearer $TOKEN" \
-H 'content-type: application/json' -d '{"name":"Grace","email":"grace@example.com"}'

A database from part 10 picks up migration 3 on the next start, and its old events keep a null actor_id. effect 4.0.6 is out, and the repo is still on 4.0.5.

Ada can create users now, and so can anyone holding one of her tokens. I’ve checked all of this with curl, by hand, which is starting to wear on me.

Next in the series: testing it with @effect/vitest.


  • Part 12 — Testing handlers with @effect/vitest: Part 11's curl table becomes six tests. HttpApiTest calls the real handlers and middleware in process, with Users in memory and a fake Tokens: no port, no database.

Footnotes

  1. securityDecode in packages/effect/src/http-api/HttpApiBuilder.ts at effect@4.0.5 returns Redacted.make(getAuthorizationCredential(...) ?? "") for the Http scheme. The same file’s makeSecurityMiddleware is what calls your bearer function with the credential. ↩

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.