refactor(auth): make every issuer screen a value of its own

The issuer's screens were written inline in its route handlers, so the
only way to look at one was to reach the condition that produces it: an
expired cookie, a refused grant, ten wrong guesses. They now live in
ui/issuer.ts and the handlers call them, with no change to copy, status
or markup.

The app's theme moves to its own module for the same reason: it can be
used without importing the issuer and its database stores.
This commit is contained in:
Wanjohi
2026-10-02 05:27:27 +03:00
parent 61eeecce43
commit 8326d88894
4 changed files with 187 additions and 115 deletions
+1 -27
View File
@@ -2,7 +2,6 @@ import type { Hyperdrive } from '@cloudflare/workers-types';
import { issuer } from '@nestri/auth/index';
import { CodeProvider } from '@nestri/auth/provider/code';
import { CodeUI } from '@nestri/auth/ui/code';
import type { Theme } from '@nestri/auth/ui/theme';
import { isDomainMatch } from '@nestri/auth/util';
import { Actor } from '@nestri/core/actor';
import { PostgresCodeStore } from '@nestri/core/auth/authorization-code';
@@ -17,6 +16,7 @@ import { Identity } from '@nestri/core/user/identity';
import { LinkedAccount } from '@nestri/core/user/linked-account';
import { sendVerificationCode } from './email.js';
import { THEME_NESTRI } from './theme.js';
/**
* Everything this issuer is handed, from a binding or from the environment.
@@ -170,32 +170,6 @@ export const allowClient = async (
return isDomainMatch(redirect, host);
};
/**
* The sign-in screen's theme.
*
* Almost everything that used to live here is now stated in
* `packages/auth/src/ui/css.ts`, which states the product's design language
* longhand. What is left here is the handful of values the
* issuer itself needs — and `primary`, which is the one colour the stylesheet
* reads back from the theme so the brand has a single source.
*
* There is no `background` and no light variant on purpose: the page is dark
* only, and the derived-colour scheme that made two schemes possible is
* exactly what rendered the sign-in field's text the colour of its own
* background.
*/
const THEME_NESTRI: Theme = {
title: 'Login | Nestri',
primary: 'hsl(12 84% 53%)',
favicon: 'https://nestri.io/images/favicon.ico',
// Mona Sans for the display line and the action, Geist for everything a
// person reads or types. Served from the Fontsource CDN because the
// self-hosted font packages need a bundler and nothing preprocesses this
// page — it is assembled as a string at request time. The family names must
// match the ones the stylesheet asks for.
css: `@import url('https://cdn.jsdelivr.net/fontsource/css/mona-sans:vf@latest/wght.css');@import url('https://cdn.jsdelivr.net/fontsource/css/geist:vf@latest/wght.css');`
};
export default {
async fetch(request: Request, env: Env, ctx?: ExecutionContext) {
Env.init(env as unknown as Record<string, unknown>);
+27
View File
@@ -0,0 +1,27 @@
import type { Theme } from '@nestri/auth/ui/theme';
/**
* The sign-in screen's theme.
*
* Almost everything that used to live here is now stated in
* `packages/auth/src/ui/css.ts`, which states the product's design language
* longhand. What is left here is the handful of values the
* issuer itself needs — and `primary`, which is the one colour the stylesheet
* reads back from the theme so the brand has a single source.
*
* There is no `background` and no light variant on purpose: the page is dark
* only, and the derived-colour scheme that made two schemes possible is
* exactly what rendered the sign-in field's text the colour of its own
* background.
*/
export const THEME_NESTRI: Theme = {
title: 'Login | Nestri',
primary: 'hsl(12 84% 53%)',
favicon: 'https://nestri.io/images/favicon.ico',
// Mona Sans for the display line and the action, Geist for everything a
// person reads or types. Served from the Fontsource CDN because the
// self-hosted font packages need a bundler and nothing preprocesses this
// page — it is assembled as a string at request time. The family names must
// match the ones the stylesheet asks for.
css: `@import url('https://cdn.jsdelivr.net/fontsource/css/mona-sans:vf@latest/wght.css');@import url('https://cdn.jsdelivr.net/fontsource/css/geist:vf@latest/wght.css');`
};
+11 -88
View File
@@ -231,6 +231,7 @@ import { DynamoStorage } from './storage/dynamo.js';
import { MemoryStorage } from './storage/memory.js';
import { Storage, StorageAdapter } from './storage/storage.js';
import { HtmlRenderer, type Renderer } from './ui/render.js';
import { IssuerScreens } from './ui/issuer.js';
import type { ChooseOption, Screen } from './ui/screen.js';
import type { Theme } from './ui/theme.js';
import { getRelativeUrl, isDomainMatch, lazy } from './util.js';
@@ -578,16 +579,7 @@ export function issuer<
const error =
input.error ??
function (err: UnknownStateError, req: Request) {
return renderer.render(
{
kind: 'message',
tone: 'danger',
heading: 'That sign-in has expired',
body: [err.message, 'Start again from wherever you were signing in.'],
status: 400
},
req
);
return renderer.render(IssuerScreens.unknownState(err.message), req);
};
const ttlAccess = input.ttl?.access ?? 60 * 60 * 24 * 30;
const ttlRefresh = input.ttl?.refresh ?? 60 * 60 * 24 * 365;
@@ -938,31 +930,11 @@ export function issuer<
* three.
*/
function expired(): Screen {
return {
kind: 'message',
tone: 'danger',
heading: 'That sign-in request has expired',
body: ['Start it again from the app.'],
status: 400
};
return IssuerScreens.deviceExpired();
}
function deviceConfirmScreen(confirmation: DeviceConfirmation): Screen {
return {
kind: 'confirm',
heading: 'Is this you?',
verify: { code: confirmation.userCode, group: 4 },
body: [
`${confirmation.clientID} is asking to sign in to your account. The code above should match the one it is showing you.`,
'If it does not, or you did not start this on a device of your own, choose Deny. Nobody can sign in as you unless you approve here.'
],
action: '/device/confirm',
// The client id is escaped by the renderer like any other text. It
// is chosen by whoever started the grant, so it is never markup.
fields: [{ kind: 'hidden', name: 'csrf', value: confirmation.csrf }],
approve: { label: 'Approve', name: 'action', value: 'approve' },
deny: { label: 'Deny', name: 'action', value: 'deny' }
};
return IssuerScreens.deviceConfirm(confirmation);
}
async function getAuthorization(ctx: Context) {
@@ -1523,32 +1495,11 @@ export function issuer<
app.get('/device', async (c) => {
const raw = c.req.query('user_code');
if (!raw) {
return auth.screen(c, {
kind: 'form',
method: 'get',
action: '/device',
fields: [
{
kind: 'segments',
name: 'user_code',
label: 'Enter the code shown in the app',
length: USER_CODE_LENGTH,
autocomplete: 'off',
autofocus: true
}
],
submit: 'Continue'
});
return auth.screen(c, IssuerScreens.deviceEnter(USER_CODE_LENGTH));
}
if (!(await guessesLeft(c.req.raw))) {
return auth.screen(c, {
kind: 'message',
tone: 'danger',
heading: 'Too many tries',
body: ['Wait a while, then start again from the app.'],
status: 429
});
return auth.screen(c, IssuerScreens.deviceTooManyTries());
}
const found = await deviceStore.byUserCode(canonicalUserCode(raw));
@@ -1557,13 +1508,7 @@ export function issuer<
// nothing, so a person mistyping once and then succeeding is not
// walking towards a lockout.
await chargeGuess(c.req.raw);
return auth.screen(c, {
kind: 'message',
tone: 'danger',
heading: 'That code is not valid',
body: ['It may have expired, or already been used. Ask the app for a new one.'],
status: 400
});
return auth.screen(c, IssuerScreens.deviceInvalidCode());
}
const authorization: AuthorizationState = {
@@ -1602,43 +1547,21 @@ export function issuer<
const form = await c.req.formData().catch(() => null);
const csrf = form?.get('csrf')?.toString() ?? '';
if (!timingSafeCompare(confirmation.csrf, csrf)) {
return auth.screen(c, {
kind: 'message',
tone: 'danger',
heading: 'That form was not the one we sent',
body: ['Start again from the app.'],
status: 400
});
return auth.screen(c, IssuerScreens.deviceForgedForm());
}
if (form?.get('action')?.toString() === 'deny') {
await deviceStore.deny(confirmation.deviceCode);
return auth.screen(c, {
kind: 'message',
tone: 'notice',
heading: 'Refused',
body: ['That sign-in request was refused. You can close this page.']
});
return auth.screen(c, IssuerScreens.deviceDenied());
}
// The store decides, not this code. If a refusal got here first the
// answer is already given and an approval must not overwrite it.
const approved = await deviceStore.approve(confirmation.deviceCode, confirmation.subject);
if (!approved) {
return auth.screen(c, {
kind: 'message',
tone: 'danger',
heading: 'Already answered',
body: ['That sign-in request has already been answered.'],
status: 400
});
return auth.screen(c, IssuerScreens.deviceAlreadyAnswered());
}
return auth.screen(c, {
kind: 'message',
tone: 'notice',
heading: 'You are signed in',
body: ['You can close this page and go back to the app.']
});
return auth.screen(c, IssuerScreens.deviceApproved());
});
app.get('/authorize', async (c) => {
+148
View File
@@ -0,0 +1,148 @@
/**
* The screens the issuer draws itself, rather than a provider.
*
* They were written inline in the route handlers, which kept each next to the
* condition that reaches it but meant the only way to look at one was to
* arrange that condition — an expired cookie, a refused grant, a code guessed
* wrong ten times. Here each is a value that can be rendered on its own, which
* is what the preview in `apps/auth/script/preview.ts` does with every one.
*
* Copy and status only. How any of them looks is `render.tsx`'s business.
*
* @packageDocumentation
*/
import type { Screen } from './screen.js';
/** The confirmation a device grant asks for, before it is approved. */
export interface DeviceConfirmCopy {
clientID: string;
userCode: string;
csrf: string;
}
export const IssuerScreens = {
/** The authorization state a request named is missing or unreadable. */
unknownState(message: string): Screen {
return {
kind: 'message',
tone: 'danger',
heading: 'That sign-in has expired',
body: [message, 'Start again from wherever you were signing in.'],
status: 400
};
},
/**
* What a device grant says once there is nothing left to answer.
*
* Written once because three different dead ends reach it — a cookie that
* timed out, a grant that expired, a confirmation that was already given —
* and the person on the other end can do the same one thing about all
* three.
*/
deviceExpired(): Screen {
return {
kind: 'message',
tone: 'danger',
heading: 'That sign-in request has expired',
body: ['Start it again from the app.'],
status: 400
};
},
deviceEnter(length: number): Screen {
return {
kind: 'form',
method: 'get',
action: '/device',
fields: [
{
kind: 'segments',
name: 'user_code',
label: 'Enter the code shown in the app',
length,
autocomplete: 'off',
autofocus: true
}
],
submit: 'Continue'
};
},
deviceTooManyTries(): Screen {
return {
kind: 'message',
tone: 'danger',
heading: 'Too many tries',
body: ['Wait a while, then start again from the app.'],
status: 429
};
},
deviceInvalidCode(): Screen {
return {
kind: 'message',
tone: 'danger',
heading: 'That code is not valid',
body: ['It may have expired, or already been used. Ask the app for a new one.'],
status: 400
};
},
deviceConfirm(confirmation: DeviceConfirmCopy): Screen {
return {
kind: 'confirm',
heading: 'Is this you?',
verify: { code: confirmation.userCode, group: 4 },
body: [
`${confirmation.clientID} is asking to sign in to your account. The code above should match the one it is showing you.`,
'If it does not, or you did not start this on a device of your own, choose Deny. Nobody can sign in as you unless you approve here.'
],
action: '/device/confirm',
// The client id is escaped by the renderer like any other text. It
// is chosen by whoever started the grant, so it is never markup.
fields: [{ kind: 'hidden', name: 'csrf', value: confirmation.csrf }],
approve: { label: 'Approve', name: 'action', value: 'approve' },
deny: { label: 'Deny', name: 'action', value: 'deny' }
};
},
deviceForgedForm(): Screen {
return {
kind: 'message',
tone: 'danger',
heading: 'That form was not the one we sent',
body: ['Start again from the app.'],
status: 400
};
},
deviceDenied(): Screen {
return {
kind: 'message',
tone: 'notice',
heading: 'Refused',
body: ['That sign-in request was refused. You can close this page.']
};
},
deviceAlreadyAnswered(): Screen {
return {
kind: 'message',
tone: 'danger',
heading: 'Already answered',
body: ['That sign-in request has already been answered.'],
status: 400
};
},
deviceApproved(): Screen {
return {
kind: 'message',
tone: 'notice',
heading: 'You are signed in',
body: ['You can close this page and go back to the app.']
};
}
};