One package for JGB Solutions apps, in tree-shakable namespaces: the generic plumbing web apps need (Cloudflare Access, Better Auth) the admin panel kit (kit/admin), the shared sign-in and account pages (kit/account) and the design system (kit/tokens, kit/ui). An app bundles only the subpaths it imports: one using kit/access never ships admin or React code (bun run check:install proves it). ESM with TypeScript types, one subpath per module, MIT licensed. The modules run anywhere with Web Crypto and fetch: Bun, Node and Cloudflare Workers (kit/auth/bun on Bun only, kit/auth/expo in React Native, kit/admin and kit/account in React 19 apps, kit/account/native in Expo).
bun add @jgb-solutions/kitCloudflare Access signs people in at the edge and passes a signed token (RS256) with each request it lets through: the Cf-Access-Jwt-Assertion header and the CF_Authorization cookie. An edge rule only covers the paths it matches, so client-side navigation, server functions and RPC calls can reach the server without passing through it. Check the token on the server for every protected call:
import { verifyAccess } from '@jgb-solutions/kit/access'
// The app's own Access application: its team domain and audience (AUD) tag.
const settings = { teamDomain: '<team>.cloudflareaccess.com', aud: '<the application AUD tag>' }
const result = await verifyAccess(request.headers, settings)
if (!result.ok) return new Response('Forbidden', { status: 403 }) // result.reason says why
result.email // the signed-in person (null for a service token)-
Fails closed. Missing settings, no token, a bad signature, the wrong issuer or audience, an expired token or keys that can't be fetched all return
{ ok: false, reason }. It never throws. -
RS256 only. The issuer must be
https://<team>.cloudflareaccess.com, and the token must carryexp,iat,issandaud. The default clock tolerance is 30 seconds. -
Keys: Access's public keys for the team, fetched from its
cdn-cgi/access/certsendpoint and cached (5-second timeout). -
Tests sign their own tokens. A test server makes a throwaway key pair and passes the public key set in
ACCESS_TEST_JWKS.accessTestKeys(env, { enabled })returns those keys only when the caller says it is a test server:const keys = accessTestKeys(process.env, { enabled: process.env.E2E === '1' && !isProductionBuild }) const result = await verifyAccess(headers, { ...settings, ...(keys ? { keys } : {}) })
-
The production guard. Anyone holding a test key could sign in where test keys are accepted. Where the production build starts, refuse to run with any test-only setting:
const problems = accessTestProblems(process.env, { production: isProductionBuild, alsoForbidden: ['E2E'] }) if (problems.length) throw new Error(problems.join('\n'))
Keep the app's own role check after this one: Access decides who may reach the app, and the app decides what they may do.
Sign-in set up once for every app: a username or email with a password, passkeys (also the way back into an account whose password is forgotten, since no email is ever sent), "Continue with Google" when its keys are set, roles with an admin panel, and the same session for the website (cookie) and the mobile app (Authorization: Bearer).
It needs better-auth and @better-auth/passkey (and @orpc/server for kit/auth/orpc). They are optional peer dependencies: install them in the apps that use auth, and an app that only uses kit/access never gets them.
bun add @jgb-solutions/kit better-auth @better-auth/passkeyimport { betterAuth } from 'better-auth'
import { tanstackStartCookies } from 'better-auth/tanstack-start'
import { authSettings, standardAuthOptions } from '@jgb-solutions/kit/auth'
import { argon2idHasher } from '@jgb-solutions/kit/auth/bun' // on Bun (Workers keep Better Auth's scrypt); fallbackVerify for older hashes, concurrency to cap hashes at once
export const auth = betterAuth(
standardAuthOptions({
appName: 'Example',
siteUrl: 'https://app.example.com',
settings: authSettings(process.env), // BETTER_AUTH_SECRET, SIGN_UP, ADMIN_EMAILS, GOOGLE_*
database: drizzleAdapter(db, { provider: 'sqlite', schema }),
admin: { ac, roles, defaultRole: 'user', adminRoles: ['admin'] }, // the app's permissions
takenUsernames: (candidates) => findUsedUsernames(candidates), // one query
usernameFallback: 'member',
localOrigins: ['http://localhost:5173'],
password: argon2idHasher(),
beforeDeleteUser: (user) => deleteEverythingOf(user.id),
lastPlugin: tanstackStartCookies(),
}),
)What the preset sets:
- Passwords: 12 to 128 characters, with no email verification and no reset link (no email is ever sent).
SIGN_UP=offcloses sign-up; existing accounts still sign in. - Usernames (Better Auth's username plugin): 3 to 30 characters, lower-case letters, digits, dots and underscores. An account made without one (Google) gets one from its name, with a number when it's taken.
- Passkeys for the site, the
localOriginsand the Android app (androidCertSha256). WithpasskeyOrigin: 'request', the request's own origin instead (the site, previews and any local port; one oftrustedBaseUrl's hosts), for apps without an Android app. - Google, when
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRETare set.GOOGLE_MOBILE_CLIENT_IDSadds the apps' clients, for ID-token sign-in. A new Google address makes a new account with a confirmed address. Joining existing accounts is "merge only confirmed" (see below). - Roles: Better Auth's admin plugin, with the app's access control. A new account whose address is in
ADMIN_EMAILSstarts as admin when it's created with Google (a confirmed address); a sign-up with that address by email and password starts as an ordinary user, so nobody can claim an admin's address first. Other first admins are promoted from the server (the app's admin script). - The mobile app: the bearer plugin.
- Limits: 60 requests a minute, tighter on sign-in, sign-up, passkeys and password changes (
RATE_LIMIT_RULES). Counts go in the database, or in a counter store withrateLimitStorage: counterRateLimit(() => redis), which counts in the server's memory while the store is down (memoryRateLimit()on its own suits a single server). - Sessions: 30 days, renewed daily, with a 5-minute cookie cache. The base URL is the request's host only for the site or a local host; anything else falls back to the site.
The app never sends email, so an address typed at sign-up is never confirmed. Someone could sign up first with another person's address and a password they know. So "Continue with Google" joins an existing account with the same address only when that account's address is confirmed: it was made with Google, or by an admin. Otherwise Better Auth refuses, and the app shows the way in:
- On the sign-in page, the refusal arrives as
?error=account_not_linkedafter Google's redirect, or as an error body from an ID-token sign-in.authErrorCode(answer)(kit/auth/rules) turns either intoACCOUNT_NOT_LINKED. The page says: An account with this address already exists. Sign in with your password, then connect Google from your account page. - On the account page, "Connect Google" calls Better Auth's
/link-socialfor the signed-in person:auth.api.linkSocialAccount({ body: { provider: 'google', callbackURL: '/account', errorCallbackURL: '/account' }, headers })on the website (go to theurlit returns), orauth.linkGoogle(idToken)in the app. The Google address may differ from the account's (username accounts have a placeholder address). Every session of the account stays (the owner proved both sides), and the account takes Google's picture if it had none. From then on, "Continue with Google" signs into it. - A Google account that already belongs to another account gives
GOOGLE_ALREADY_LINKED. A Google address Google didn't verify givesGOOGLE_EMAIL_NOT_CONFIRMED.
When a Google sign-in joins a confirmed account that also has a password, every session of that account ends: one someone else held doesn't carry on. A browser signed into another account counts as such a sign-in, not as the owner connecting.
Everything the preset uses is exported on its own, for an app that needs a different mix (authSettings, trustedBaseUrl, passkeyOrigins, androidOrigin, assetLinks, googleProvider, CONFIRMED_ACCOUNT_LINKING, freeUsername, afterAccountSaved, pictureFromIdToken, signedInFlagHook, asPublicRequest, toAuthUser). What stays in the app is its own: its name and address, database and schema (bunx auth@latest generate), roles and permissions, texts, pages, and its Google, Android and Access identifiers.
import { authMiddleware } from '@jgb-solutions/kit/auth/orpc'
const { withUser, requireUser, requireAdmin } = authMiddleware({
viewer: async () => toAuthUser((await auth.api.getSession({ headers }))?.user, roleOf), // cookie or Bearer
canOpenAdmin,
adminCheck: async () => (await verifyAccess(headers, access)).ok, // optional: Cloudflare Access too
})requireUser answers UNAUTHORIZED, and requireAdmin answers FORBIDDEN for a role that can't open the admin panel or a failed adminCheck. Both mark the answer private, no-store.
USERNAME, PASSWORD, usernameProblem, isPlaceholderEmail, placeholderEmail, defineRoles({ roles, defaultRole, adminPanel }) (roleOf, canOpenAdmin, isRole), the AuthUser type, authErrorCode with ACCOUNT_NOT_LINKED, GOOGLE_ALREADY_LINKED and GOOGLE_EMAIL_NOT_CONFIRMED, avatarSrc (https pictures only, sized) and avatarInitials.Also usernameErrorCode (a username's problem as Better Auth's code: USERNAME_TOO_SHORT, USERNAME_TOO_LONG, INVALID_USERNAME), displayNameProblem(name, max = 50), defineSignInReasons(list) (an allow-list for ?reason= or #done=: reasonOf(value) answers a listed code or undefined), and safeRedirect(value) / isSafeRedirectPath(path) for "back to where you were" after sign-in: a path on this site only, refusing //host, backslashes and control characters, also percent-encoded. No dependencies.
Sign-in, sign-up, passwords, passkeys, Google, deleting one's own account and the admin's user management, framework-free. Give it the Better Auth instance and the request's headers; call it from server functions or oRPC procedures. Failures are codes ({ ok: false, code }), Better Auth's own or AUTH_SERVER_CODES, for the app to word.
import { authServer } from '@jgb-solutions/kit/auth/server'
const accounts = authServer({
auth: getAuth,
headers: getRequestHeaders,
roleOf,
canOpenAdmin,
rateLimit: { storage: rateLimitStorage }, // required: the store given to standardAuthOptions; 'off' only for E2E
})
await accounts.viewer() // the signed-in person, or null (also when suspended); { fresh: true } skips the cookie cache
await accounts.signIn({ login, password }) // username or email; a placeholder address never signs in
await accounts.signUp({ username, password, email }) // no email: a placeholder address
await accounts.changePassword({ currentPassword, newPassword }) // signs out the other devices
await accounts.passkeys() // newest first
await accounts.googleStartUrl({ redirect, home: '/account', signInPath: '/sign-in' }) // redirect checked with safeRedirect
await accounts.deleteOwnAccount({ password }) // without a password (Google): a sign-in from the last 5 minutes, else REAUTH_REQUIRED
await accounts.admin.listUsers({ page, pageSize: 25, search })
await accounts.admin.ban({ userId }) // also setRole, unban, resetPassword: never on the admin's own accountRate limits. The client's address comes from ipAddressHeaders (cf-connecting-ip by default): that header is trustworthy only when every request comes through Cloudflare. A server reachable directly must list the header its own proxy sets, or anyone can pick a new address per request. Better Auth limits only requests to its own routes (/api/auth/…), never a direct auth.api call, so a server function calling it is unthrottled. authServer counts each attempt itself, in the same store and under Better Auth's own keys (<ip>|<path>, the address read the way the instance reads it), so the two add up. Password sign-in also counts per login, through either door: standardAuthOptions adds accountSignInLimit (ACCOUNT_SIGN_IN_RULE, 30 in 15 minutes per login, its username and its address each, keyed by a hash), a Better Auth hook that runs for /api/auth requests and direct calls alike, so a new address per attempt doesn't reset it. It uses rateLimitStorage (in memory with the database store). rateLimit: 'off' throws on a production server unless E2E=1. Over the limit: TOO_MANY_REQUESTS with retryAfter in seconds.
Admin calls read the session fresh and go through toAuthUser, so a suspended admin is out at once. authResult(fn) turns any other Better Auth call into the same { ok, code }.
CDN cache keys ignore cookies, so a signed-in page stored once reaches the next visitor. hasSession(cookieHeader, sessionCookieNames(prefix)) spots a session by exact cookie name (with Better Auth's cookiePrefix, if the app changed it). privatePaths(['admin', 'account', 'sign-in']) matches those pages and what's under them, in every language folder (/fr/account). makePrivate(response) sets private, no-store and drops cdn-cache-control and cloudflare-cdn-cache-control. authRouteHandler(getAuth, { publicRequest }) serves /api/auth/* with every answer private.
redisCounterStore(redis, 'app:') is a counter store for counterRateLimit, with any client that has incr and expire (Bun's RedisClient, ioredis). For oRPC's Redis limiter, evalWithFallback(() => redis.send('EVAL', …)) answers RATE_LIMIT_SCRIPT_FALLBACK ([1, 0, 0]: allowed, nothing counted) while the store is away. From oRPC 2.0.0-beta.53 the old [0, 0] reads as refused, and every call failed.
No dependencies: the app passes @simplewebauthn/browser in, loaded only when a passkey button is pressed.
import { afterSignIn, createPendingAction, passkeyClient, readSignedInFlag } from '@jgb-solutions/kit/auth/browser'
const passkeys = passkeyClient({ webauthn: () => import('@simplewebauthn/browser') }) // Better Auth's /api/auth/passkey
await passkeys.signIn() // { ok: true } or { ok: false, code } (CANCELLED, NETWORK, Better Auth's codes)
await passkeys.add('My laptop')
export const pending = createPendingAction<'favorite' | 'follow'>() // what a signed-out visitor tapped, in this tab only
pending.set({ kind: 'favorite', name: song.title, run: () => addFavorite(song.id) })
const done = await pending.finish('signed-in') // after sign-in: runs it, answers its kind
location.assign(afterSignIn(redirect, done)) // …#done=favorite for the confirmation
readSignedInFlag('example_in') // the readable flag cookie standardAuthOptions sets (a hint; the server checks)import { randomUUID } from 'expo-crypto'
import * as SecureStore from 'expo-secure-store'
import * as Passkeys from 'react-native-passkeys'
import { createMobileAuth } from '@jgb-solutions/kit/auth/expo'
// randomId: Hermes has no global crypto; sign-up without an email needs one for its placeholder address.
export const auth = createMobileAuth({
origin: 'https://app.example.com',
storage: SecureStore,
tokenKey: 'example.session',
fetchMe,
randomId: randomUUID,
})
const session = useSyncExternalStore(auth.subscribe, auth.getSession)
await auth.signIn('maria', password) // or an email address
const nonce = await auth.googleNonce() // { ok: true, nonce } (single use) or { ok: false, code }: report the code
await auth.signInWithGoogle(idToken, nonce.ok ? { nonce: nonce.nonce } : {}) // from the app's Google Sign-In SDK, asked with the nonce
await auth.linkGoogle(idToken) // signed in: connect Google from the account screen
await auth.signInWithPasskey(Passkeys)
new RPCLink({ url, headers: auth.authHeaders }) // Bearer on every RPC call; in its error interceptor: auth.handleUnauthorized(error)restore() at launch checks the saved token with the server. Offline, the session is unverified: never signed in (show signed-out or cached screens) and restore() again when back online. Any UNAUTHORIZED answer passed to handleUnauthorized forgets the token.
On Android, googleIdToken(nativeModule, webClientId, nonce) gets the ID token from the phone's Google account sheet (the app's own Credential Manager module: signIn(serverClientId) answering { idToken }, rejecting with ERR_CANCELLED or ERR_NO_ACCOUNT). It answers { ok: true, idToken }, or CANCELLED, NO_GOOGLE_ACCOUNT, GOOGLE_UNAVAILABLE (no module or client ID), or GOOGLE_FAILED with a detail for the error tracker.
Failures come back as codes (INVALID_USERNAME_OR_PASSWORD, ACCOUNT_NOT_LINKED, GOOGLE_ALREADY_LINKED, TOO_MANY_REQUESTS, NETWORK, CANCELLED…), and the app words them. The module has no dependencies: the app passes in its secure storage and passkey modules.
English, French, Spanish and Haitian Creole (en, fr, es, ht) for websites and Expo apps. No dependencies and no framework: it runs in browsers, Workers, Bun and Hermes. English has no URL prefix; the others live under /fr, /es and /ht.
import {
createTranslator,
defineCatalog,
localizedPath,
alternates,
negotiate,
suggestLocale,
LOCALE_COOKIE,
} from '@jgb-solutions/kit/i18n'
// English is the source: write it `as const`, so keys and {placeholders} are typed.
export const en = {
home: { title: 'Welcome', greeting: 'Hello, {name}!' },
items: { count: { one: '{count} item', other: '{count} items' } },
} as const
// A translation has the same shape. A missing key, or an extra key, is a type error.
export const fr = defineCatalog<typeof en>()({
home: { title: 'Bienvenue', greeting: 'Bonjour, {name} !' },
items: { count: { one: '{count} article', other: '{count} articles' } },
})
const t = createTranslator('fr', fr, en) // en answers when a fr leaf is empty
t('home.greeting', { name: 'Ana' }) // 'Bonjour, Ana !'
t('items.count', { count: 1200 }) // '1 200 articles' (plural rules and number format of the locale)
// Without Intl.PluralRules (Hermes on Android), the same plural forms come from cldrPluralCategory.
t('home.greeting') // type error: needs { name }
// SEO: one URL per language, and the hreflang links for <head>.
localizedPath('/about', 'es') // '/es/about'
alternates('/about', 'https://example.com') // en, fr, es, ht and x-default
// Suggest, never redirect: Google advises against redirecting by browser language.
const offer = suggestLocale({ acceptLanguage: request.headers.get('accept-language'), current: 'fr', chosen: cookieValue })
// null: no bar. 'es': show "View this page in Español?", and on a click set the LOCALE_COOKIE cookie and go to localizedPath(path, 'es').Also: localeFromPath, stripLocale, defaultLocaleRedirect (the 301 target for an /en/… address), isLocale, negotiate, LOCALES, LOCALE_NAMES (each language in its own words). Placeholders are {name}; a plural leaf has one and other (plus zero, two, few, many where a language needs them) and takes count. Keep the catalogs honest in a test with checkCatalog(en, fr): it lists missing and extra keys, empty strings, plurals without other, and placeholders that differ from English.
The admin panel kit for JGB Solutions apps: a React shell, data blocks (sortable tables, rows per page), forms and SVG charts, styled once, accessible (WCAG 2.1 AA), phone-ready, light and dark. Each app builds its own pages from it. It was @jgb-solutions/admin until 0.1.5; from kit 0.3.0 it lives here (import … from '@jgb-solutions/kit/admin').
- In: the shell, navigation, data blocks, forms, actions and charts every admin needs.
- Not in: any app's pages, data, roles or rules. Components take data and callbacks; the app fetches, checks permissions on the server, and decides what happens. No business logic, secrets, app IDs or infrastructure details.
The look, "Bento + Daylight's details" (2026-11-24): rounded tiles of different sizes on a tinted canvas, a dark hero tile, a floating dark sidebar and a floating dock on phones, with a labelled sidebar, real table headers, an inline role picker and an activity feed.
bun add @jgb-solutions/kitReact 19 is an optional peer dependency: only kit/admin needs it. Import the stylesheet once, and load the two fonts (or let the fallbacks stand in):
import '@jgb-solutions/kit/admin/styles.css'
import { AdminShell, PageHeader, Button, TopSearch, ThemeToggle, icons } from '@jgb-solutions/kit/admin'
// Fonts: Bricolage Grotesque (700, 800) and Figtree (400, 500, 600), from Google Fonts or self-hosted.
export function AdminLayout({ children }: { children: React.ReactNode }) {
return (
<AdminShell
app={{ name: 'Example', mark: 'E' }}
brand="#6b4ce6"
nav={[
{
label: 'Manage',
items: [
{ key: 'overview', label: 'Overview', href: '/admin', icon: <icons.home />, current: true },
{ key: 'users', label: 'Users', href: '/admin/users', icon: <icons.users />, count: 2481 },
],
},
{ placement: 'end', items: [{ key: 'settings', label: 'Settings', href: '/admin/settings', icon: <icons.gear /> }] },
]}
user={{ name: 'Maya Reyes', role: 'Admin' }}
// With a router, render its own link: renderLink={({ item, children, ...rest }) => <Link to={item.href} {...rest}>{children}</Link>}
>
{children}
</AdminShell>
)
}Every class is prefixed ja- and every token lives on .ja-root (AdminShell's element): the admin never restyles the rest of the app.
AdminShell: the frame. Desktop: the floating dark sidebar. At 760 px and below: a top bar (the app's mark, the theme switch,mobileActions) and the floating dock. Holds the theme and the app's brand colour.brand: a hex colour. Text on it (buttons, the current page) is white or ink, whichever reads better (inkOn).nav: sections of items (key,label,href,icon, optionalcount,current). Sections withplacement: 'end'sit at the bottom.dockItems: the keys the phone's dock shows (at most 5; default the first 5).renderLink: renders a link with the app's router. Default<a href>.- Theme: light, dark or the system's (default). Remembered in this browser, or controlled with
themeandonThemeChange(e.g. kept in a cookie so the server renders it). Server rendering showsdefaultTheme("system": the CSS follows the system's dark mode with no script).
Sidebar: collapses to an icon rail, remembered per browser. In the rail, labels become tooltips and stay the links' names; counts over 99 show as "99+".Dock: up to 5 items, icon over label.PageHeader: the page's one h1, a line of context, desktop-onlytools(search, theme, notifications) andactions(one primary).TopSearch,useAdminTheme().ThemeToggle: Light, Dark or Match system, a radio group. The phone's top bar has one; put another in the sidebar withsidebarFooter={<ThemeToggle tone="night" />}(names shown; one cycling button when the sidebar is collapsed).
BentoandTile(spanof 12,rowSpan,phoneSpanof 2,tone="plain" | "night" | "sun", optionaltitleandactions); a titled tile is a region named by its title).StatTile: label, number,delta(up or down, coloured by whether it's good news),note, and aMeterorAvatarStackinside.HeroChartTile: the dark tile with the big number, its delta, a period switch (SegmentedControl) and aLineChart.DataTable: column headers, any cell (PersonCell,StatusBadge,RowAction…), rows that become cards on phones (each column'sphonesetting places it), skeleton rows while loading, an empty state that says what to do, and a one-second highlight for changed rows (flash).FilterTabsandPaginationsit around it (Paginationcan offer "Rows per page" withpageSizeandonPageSize;PageSizealone goes beside a keyset pager). Sortable columns: give a columnsort(compare: byText(...)orbyNumber(...),first: 'desc'for numbers), keep the sort in the app (sort,onSortChange, e.g. in the URL), and passsortRowswhen the table holds all the rows; for a long list, sort on the server and pass the page. Phones get a "Sort by" list.ActivityFeed: icon, sentence and time, grouped by day; loading and empty states.LineChart: one series, a fading fill, the last point marked, labels underneath, and a table of the values for screen readers.
TextInput,TextArea,Select(native), each with itslabel,hintanderrortied to the control;Fielddoes the same for any other control; an error is read out when it appears. Put a form inside a tile in<form className="ja-form">.Checkbox, andSwitchfor settings that apply at once (role="switch").ConfirmDialog: the browser's own<dialog>(focus stays inside, Escape and the backdrop cancel, focus returns), a button that names the action ("Suspend Leo Martin"), destructive styling.useToast():toast.done('Suspended Leo Martin.')(gone after 4 s) andtoast.error(…)(stays until dismissed); above the dock on phones.RolePicker: an inline role select for a table row; roles listed inconfirmask first ("Make Ada Okafor an Admin?").BanControl: suspend with an optional reason, after a confirmation, or restore.
LineChart: one series, a fading fill, the last point marked, labels underneath (color="sun" | "brand").BarChart: one series, or two (this period and the last, with a legend).- Both stretch to their tile, take an accessible
label, and add a table of the values for screen readers.
Button(primary,quiet,danger;small),IconButton(always named bylabel; optionaldot).Avatar: a picture or initials, with a colour pair kept per name.icons: a small line-icon set (24×24,currentColor). Any other icon works as a ReactNode.
CSS custom properties on .ja-root, light by default, dark with data-theme="dark" or the system's dark mode. Apps set --brand (AdminShell's brand); the rest are the kit's.
| Token | Light | Dark | Use |
|---|---|---|---|
--brand |
the app's (example #6b4ce6) |
same | current page, primary buttons, meters, links |
--brand-ink |
white or ink, picked for contrast | same | text on --brand |
--sun / --sun-ink |
#ffc84a / #4a3500 |
same | the kit's highlight: the hero chart line, one highlight tile, badges |
--canvas |
#eceaf6 |
#121022 |
page background |
--tile / --tile-sunk |
#ffffff / #f6f5fb |
#1c1930 / #24203a |
tiles, inputs; rows and fields inside tiles |
--night |
#1f1b33 |
#0d0b18 |
sidebar, hero tile, dock, toasts |
--ink / --muted |
#1c1930 / #6b6785 |
#f1effa / #a39fbf |
text, secondary text |
--line |
#e4e1f0 |
#2e2a47 |
control borders |
--good / --warn / --bad |
#158150 / #946200 / #b42318 |
#4cc38a / #f0b429 / #ff7a6b |
status: active, invited, suspended; deltas |
Every text pair meets WCAG AA; src/contrast.test.ts checks them, and the E2E tests run axe in light and dark. Two values differ slightly from the approved mockup for that reason: --muted (#6d6987 was 4.39:1 on the canvas) and --good (#18915a was 3.7:1 on rows).
Type: Bricolage Grotesque (700/800) for titles and numbers (tabular-nums), Figtree (400/500/600) for the rest. Sentence case everywhere. Shape: tiles 24 px (20 on phones), controls 12 px, pills. Motion only in answer to an action, and none with prefers-reduced-motion.
One sign-in, sign-up and account layout for every app, chosen by the owner (2026-12-04): the same field order, buttons, links and wording rules everywhere, on the web and in Expo. Each app changes only the look (colours, fonts, radius) and the words.
- In: the sign-in, sign-up and "signed in" cards, and the account page (Profile, the app's own cards, Passkeys, Google, Password, Delete account), in a fixed order.
- Not in: sign-in itself. Every button calls the app's action, which answers
{ ok: true } | { ok: false, code }(kit/auth/server'sAuthResult). The kit words the code with the app'sAccountText(errorText), and never shows a raw error. On success the app goes where it wants; the panel stays busy until it does.
import '@jgb-solutions/kit/account/styles.css'
import { AccountRoot, SignInPanel, accountTextEn } from '@jgb-solutions/kit/account'
export function SignInPage() {
return (
<AccountRoot scheme="dark" theme={{ brand: '#d42320', radiusButton: '12px' }}>
<SignInPanel
text={accountTextEn}
reason={reasonText} // "Sign in to save it to your favorites", or undefined
initialError={search.error} // Google's ?error= code
google={() => startGoogleSignIn({ data: { redirect } })} // leave out when Google is off
passkey={signInWithPasskey}
onSignIn={(input) => signIn({ data: input })}
signUpHref="/sign-up"
renderLink={({ href, className, children }) => (
<Link to={href} className={className}>
{children}
</Link>
)}
/>
</AccountRoot>
)
}SignUpPanel and SignedInPanel work the same way. AccountPage takes the person, the passkeys, and one action per change; afterProfile holds the app's own cards (notifications, a callout). Deleting an account asks for the password, or, for an account made with Google, a Google sign-in from the last 5 minutes (confirm: { mode: 'reauth', fresh, onReauth }, matching authServer's REAUTH_REQUIRED). The sections (ProfileSection, PasskeysSection, GoogleSection, PasswordSection, DangerSection) are exported for a page that needs them apart.
Words: AccountText holds every string; words with a number or a name are functions. Pass a translation, or { ...accountTextEn, … } with a few lines changed. Dates print in UTC, so the server and the browser print the same.
Look: AccountRoot's theme sets these tokens (CSS variables on .jac-root; every class is prefixed jac-, so nothing outside changes). Light by default, dark with scheme="dark" or the system's dark mode (dark by default is a near-black grey). brandInk is picked for contrast when the brand is a hex colour.
| Theme key | Token | Light default | Dark default |
|---|---|---|---|
brand / brandInk / brandText |
--jac-brand / -brand-ink / -brand-text |
#2f54c8 / white / #2a4bb3 |
same / same / brand mixed light |
page / surface / raised |
--jac-page / -surface / -raised |
#f4f4f6 / #ffffff / #ececf0 |
#0b0b0e / #15151a / #212127 |
line / fieldLine |
--jac-line / -field-line |
#dcdce3 / #a9a9b4 |
#2d2d34 / #55555e |
ink / muted |
--jac-ink / -muted |
#17171c / #5b5b66 |
#eeeef1 / #aaaab2 |
good / warn / bad / info |
--jac-good / -warn / -bad / -info |
AA on cards | AA on cards |
radiusCard / radiusControl / radiusButton |
--jac-radius-card / -control / -button |
16px / 12px / 12px | same |
fontDisplay / fontBody |
--jac-font-display / -body |
the system's sans | same |
Google's button keeps Google's own white style and mark in every theme (its branding rules).
SignInOrUp (sign-in and sign-up on one screen, with the mode link), AccountProfile (the profile, passkeys, Google, the app's links, Sign out, and Delete account behind a second step) and the pieces (NativeField, NativeButton, NativeGoogleButton, NativeNotice, NativeError, NativeAvatar). Same AccountText, same actions; the theme is a plain object (accountNativeDark or accountNativeLight, with your colours, radius and fonts). Needs react-native and react-native-svg (Google's mark), both optional peer dependencies.
One typed theme object per app is the source for both the website's CSS variables and the Expo app's colours. No imports: it runs in browsers, Workers, Bun and Hermes.
import { checkTheme, nativeTheme, themeCss, type Theme } from '@jgb-solutions/kit/tokens'
export const theme: Theme = {
name: 'nightcast',
radius: 12, // the one radius an app sets: buttons and inputs use it; chips, cards and sheets derive from it
dark: { background: 'oklch(15% 0.008 285)', foreground: 'oklch(95% 0.004 285)', primary: 'oklch(56% 0.21 28)' /* … */ },
}
checkTheme(theme) // { errors: [], warnings: [] }: WCAG 2.2 AA, in every scheme the theme has
themeCss(theme) // the website's theme file
nativeTheme(theme, 'dark') // { colors: { background: '#0b0b0e', … }, radius, space, fontSize, … } for React Native- Colours follow shadcn's names: a surface and its
-foreground(--background,--card,--primary,--muted,--accent,--destructive,--border,--input,--ring, the--sidebar-*and--chart-*sets), plus--primary-text(brand-coloured text that passes on the page),--success,--warningand--info. Values areoklch()or hex. Popover, chart and sidebar colours are optional and fall back inside the same scheme. - Scales are the same in every theme (
@jgb-solutions/kit/tokens.css):--font-size-*and--line-height-*(12 px is the floor),--space-*on a 4 px step,--control-sm|md|lg(anddata-density="compact"),--hit-min(44 px),--duration-*and--easing-*(durations drop to 1 ms with reduced motion). A theme adds--radiusand what derives from it (--radius-chip,--radius-control,--radius-card,--radius-sheet,--radius-pill),--elevation-1to-3,--font-body,--font-display,--font-codeand--heading-weight. - No name collides with Tailwind 4, which owns
--color-*,--text-*,--radius-sm…,--font-sans,--shadow-*and--ease-*on:root.@jgb-solutions/kit/tokens/tailwind.cssmaps the tokens into Tailwind (bg-primary,text-muted-foreground,rounded-lg,font-heading), and a test compiles it with Tailwind. - Light and dark: a theme has a light set, a dark set or both. With both, light is on the root, dark under
data-theme="dark"(or thedarkclass) and under the system's dark mode unlessdata-theme="light"is set.color-schemeis always set. - One theme per page. A page loads the scales and exactly one theme for its root.
themeCss(theme, { scope })puts a second theme on a part of the page: the admin theme ships scoped to[data-kit-theme="admin"], so the admin keeps its look inside an app with another one. - The contrast check (
checkTheme) is what a theme passes before it ships: text 4.5:1, control borders and focus rings 3:1, and the status tints the stylesheet mixes. It warns when the brand looks like the danger colour (delete buttons stay outline) and when the brand is as pale as the page (filled buttons need an edge). - Shipped themes:
neutralTheme(…/tokens/themes/neutral.css) andadminTheme(…/tokens/themes/admin.css), each light and dark. The admin's light values are starting values until the reference measurements are in.
/* the app's global stylesheet */
@import 'tailwindcss';
@import '@jgb-solutions/kit/tokens.css';
@import '@jgb-solutions/kit/tokens/tailwind.css';
@import '@jgb-solutions/kit/ui/core.css' layer(components);
@import './theme.css'; /* themeCss(theme), written by the app's build */Plain HTML elements with data-slot, data-variant and state attributes, styled by @jgb-solutions/kit/ui/core.css from the page's tokens. No behaviour library, no class strings and no runtime styles: each renders on the server as it will look, and an app bundles only the ones it imports (bun run check:size: a Button costs about 0.5 kB gzipped, all of them under 3 kB, the stylesheet under 5 kB). Names, parts and variants follow shadcn's.
-
Components:
Button(primary,secondary,outline,ghost,link,destructive,destructive-solid;sm,md,lg,icon,icon-sm;busy),Badge,ChipandChipCount,Cardand its parts (CardHeader,CardTitle,CardDescription,CardAction,CardContent,CardFooter,CardLink),Avatar,Fieldand its parts (FieldLabel,FieldDescription,FieldError,FieldGroup,FieldSet,FieldLegend),Input,Textarea,Checkbox,Radio,Switch,NativeSelect,Alertand its parts,Emptyand its parts,Skeleton,Spinner,Separator,Kbd,VisuallyHidden. -
Dialogs and drawers are the browser's own
<dialog>, opened as a modal:Dialog,AlertDialog,ConfirmDialogandDrawer(side:bottom,top,start,end), withDialogHeader,DialogTitle,DialogDescription,DialogBody,DialogFooter,DialogCloseandDrawerHandle. The browser keeps focus inside, makes the page behind inert, and closes on Escape and on the phone's Back; the kit adds the exit animation in every browser, a press outside to close (dismiss:any,escape,none), focus back to the opening button (finalFocus, or{...focusBackTo(button)}), and the title and description wired to the dialog's name.data-autofocuson a field or button says where focus starts. No behaviour library and no inline styles: a confirm costs about 2 kB gzipped and opens with no loading step.const [open, setOpen] = useState(false) <Button variant="destructive" onClick={() => setOpen(true)}>Delete</Button> <ConfirmDialog open={open} onOpenChange={setOpen} title="Delete this station?" description="This can't be undone." cancelLabel="Keep it" confirmLabel="Delete station" tone="destructive" onConfirm={deleteStation} />
ConfirmDialogstarts on Cancel, ignores a press outside, and stays open and busy whileonConfirm's promise runs; if it rejects, the dialog stays open. Itstone="destructive"is the one place for the solid red button (--destructive-solid, which a dark theme sets to a strong red). To know: where the browser has no@starting-style(Safari before 17.5) a dialog appears without its enter animation; in Safari the page behind can still scroll under a finger at the end of a sheet; a drawer closes by its buttons, Escape or a press outside, not by a swipe. -
renderdraws a component as another element, which keeps its own meaning:<Button render={<a href="/docs" />}>. -
Styling. Every rule sits inside
:where(), so it weighs nothing: a class of yours always wins, and with Tailwind the stylesheet goes in the components layer so utilities win too. An app changes the look with its theme, with the component tokens (--button-weight,--card-shadow,--card-border,--badge-radius,--chip-radius,--avatar-radius,--field-bg) or by styling a slot in its own CSS ([data-slot='button'] { … }).classNameis for layout. -
Accessibility. Native controls, restyled: keyboard, forms and screen readers work as they always do. One 2 px focus ring everywhere. A
Fieldwires its label, hint and error to its control on the server. On a touch screen every control is at least 44 px.destructiveis an outline, so delete never looks like the main action, whatever the brand colour. Status is never colour alone. -
Words in the four languages every app ships:
uiTextEn,uiTextFr,uiTextEs,uiTextHt(each its own export, so a page bundles one). -
Content policy. The stylesheet has no images and no inline styles: a strict Content-Security-Policy needs no exception for it.
Parts a media or reference site is built from, in kit/ui like the rest (no behaviour library), with their own stylesheet so a page without them doesn't carry their rules:
@import '@jgb-solutions/kit/ui/core.css' layer(components);
@import '@jgb-solutions/kit/ui/patterns.css' layer(components);-
Rail: a row that scrolls sideways. No scrollbar; two arrows at the top right on every screen size (compact on touch screens, with a 44 px touch area), each disabled at its end, both hidden while the whole row fits. Swiping, the trackpad and the keyboard still scroll it, and it stays a real list.<Rail> <RailHeader> <RailHeading> <RailTitle>New this week</RailTitle> </RailHeading> <RailMore render={<a href="/new" />}>{text.seeAll}</RailMore> <RailArrows previous="Scroll new this week back" next="Scroll new this week on" /> </RailHeader> <RailTrack> {items.map((item) => ( <RailItem key={item.id}>…</RailItem> ))} </RailTrack> </Rail>
layout="inline"puts a row of chips and its arrows on one line.--rail-item-widthand--rail-gapsize it. -
ShareButtons: WhatsApp, Facebook, X, Telegram, Pinterest (when the page has a picture), LinkedIn, email, copy link, then the phone's share sheet where the browser has one. Plain links that open in a new tab; no third-party script. Serve the icons once: import@jgb-solutions/kit/ui/share-icons.svgas a URL with your bundler and pass it assprite. To colour one network, set--share-toneon[data-slot='share-button'][data-network='…'](check its contrast in both schemes).The email link is written between
<!--email_off-->comments: Cloudflare's email obfuscation otherwise rewrites everymailto:link into one that works only after its script runs. -
Poster: a cover (square), an upright poster (portrait) or a still (wide). The box keeps its shape before the picture arrives, and shows the title's initials on a colour made from the title when there is none. -
AdSlot: the frame around one ad. It reserves the height (banner,leaderboard,rectangle,fluid, or--ad-height), so an ad never moves the page, and shows ahousead (one of your own products, a plain link) until the network marks its element as filled (data-ad-status="filled", which AdSense sets).enabled={false}renders nothing and reserves nothing.pickHouseAd(ads, path)gives a page the same house ad every time. Needs:has()(every browser on our floor has it).Where slots go is the page's job: never before the first block of real content, and never before the third result of a search.
Self-contained functions a test runner sends into the page, so every app holds the same line. No dependency.
import { adsAfterContent, checkTouchTargets } from '@jgb-solutions/kit/testing'
// At a phone size, on a touch device profile.
const report = await page.evaluate(checkTouchTargets, { within: 'header, main' })
expect(report.small).toEqual([]) // controls a finger can't reach (under 44 px each way)
expect(report.covered).toEqual([]) // buttons under a neighbour's touch area
expect(report.tiny).toEqual([]) // text under 12 px
expect(await page.evaluate(adsAfterContent, { before: 1 })).toEqual([])A control counts by its box or by the touch area a ::before / ::after gives it. Links inside a sentence are left out.
What opens next to a button, on UI SDK's behaviours (focus, dismissal, positioning, ARIA) and styled by @jgb-solutions/kit/ui/overlays.css from the same tokens: Menu (with AnchoredMenu), Popover and Tooltip, each with its parts. Needs @ui-sdk/core and @ui-sdk/react at the exact version in peerDependencies (optional peers: apps that don't import this module don't install them). Dialogs and drawers are not here: they are in kit/ui, on the browser's own <dialog>.
This is the only part of the design system that carries a behaviour library (about 70 kB gzipped for all three), so it stays out of an app's first load. Each menu or popover lives in its own file and opens through three helpers from kit/ui, which carry none of that code:
// AccountMenu.tsx: loaded later
import { AnchoredMenu, MenuContent, MenuItem } from '@jgb-solutions/kit/ui/overlays'
import { focusBackTo, type OverlayProps } from '@jgb-solutions/kit/ui'
export default function AccountMenu({ open, onOpenChange, anchor }: OverlayProps) {
return (
<AnchoredMenu open={open} onOpenChange={onOpenChange} anchor={anchor ?? null} onAction={choose}>
<MenuContent {...focusBackTo(anchor)} align="end">
<MenuItem value="account">Your account</MenuItem>
<MenuItem value="sign-out" destructive>
Sign out
</MenuItem>
</MenuContent>
</AnchoredMenu>
)
}
// The page: in the first load
import { Button, LazyOverlay, lazyOverlay, useOverlay } from '@jgb-solutions/kit/ui'
const accountMenu = lazyOverlay(() => import('./AccountMenu'))
function AccountButton() {
const menu = useOverlay(accountMenu, { popup: 'menu' }) // fetches the code when the browser is idle, or on hover, focus or touch
return (
<>
<Button variant="secondary" {...menu.triggerProps} busy={menu.loading}>
Account
</Button>
<LazyOverlay state={menu} />
</>
)
}- The button is plain HTML from the first paint. Nothing of the menu renders, on the server or in the browser, until it is first opened. A failed download closes it and the next press tries again.
- A popover opens next to its button with
<PopoverContent {...anchoredTo(anchor)}>;useOverlay(menu, { popup: 'menu' })also opens a menu with the arrow keys, its first item focused. - A menu, popover or tooltip works inside a
Dialog: it draws above it, and Escape closes it before the dialog. - The page's global stylesheet starts with
@layer ui-sdk;. Under a Content-Security-Policy, pages with a menu, popover or tooltip needstyle-src-attr 'unsafe-inline'and a<meta property="csp-nonce" nonce="…">: UI SDK positions popups with inline styles. The core components, dialogs and drawers included, need neither.
Typed clients for Speed, the service that does heavy work (drawing images) for an app's server, one per feature, over gRPC-Web on fetch (Connect-ES 2, protobuf-es 2): Cloudflare Workers, Bun and Node. Needs @connectrpc/connect, @connectrpc/connect-web and @bufbuild/protobuf (optional peers). The first feature is social cards, the share images for pages without one of their own:
import { createSocialCardsClient } from '@jgb-solutions/kit/speed'
const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) // once per isolate or process
const image = await cards.getCardOr(
{ locale: 'en', page: { title: 'Animals', emoji: ['🐶', '🐱'] } },
{ url: 'https://example.com/share.png' },
)
// { url, width, height, fromSpeed }- Speed never breaks a page.
getCardOr(and every feature's…Orcall, built onwithFallback) never throws and never waits past the deadline (1.5 s, no retries): when Speed is slow, failing or not set up yet (noSPEED_URL), it returns the app's own image (the logo on the brand colour is the recommended share image) or a colour, sized to the format. A circuit breaker skips Speed for 30 s after 3 failures in 30 s.onFallback(reason)counts them:timeout,error,breaker-open,not-configured. - The same input always gives the same URL: cache it (KV, the Cache API or SQLite), but a fallback (
fromSpeed: false) for 60 s at most. Prerendered pages ask while they are built. getCardis the call without the failover:{ url, width, height, contentType, created, key }, or aSpeedErrorwith acode.SPEED_TOKENis the app's key: server-side only. Mobile apps never call Speed; they ask their site, through its oRPC procedures.
More in docs/speed.md: the failover, Workers and Bun, caching, updating the API.
In: generic plumbing that several apps need in the same shape, written once and tested: checking a signed token, parsing a header, a retry or rate-limit helper, a typed client for a public protocol. Every module:
- takes its settings from the caller (team names, audiences, URLs, limits);
- has full unit tests;
- has no side effects at import, and no dependency it doesn't need.
Never in:
- Business logic: how an app works, decides, charges or ranks. That stays in the app.
- Secrets of any kind: keys, tokens, passwords, signing material.
- App and account identifiers: Access team names and AUD tags, account or zone IDs, database or bucket names, app slugs.
- Infrastructure details: hosts, IP addresses, server names, internal URLs, deploy setup.
- Personal data, or real addresses outside
example.com.
bun run check:package scans every file that would be published, before each publish and in CI. It fails on an Access team domain other than the examples, on a 32- or 64-character hex ID, on an address outside example.com, on any file besides dist/, the README, the changelog, the license and package.json, and on a module importing more than it may (kit/access jose alone; kit/auth/rules, kit/auth/browser, kit/auth/cache, kit/auth/redis, kit/auth/expo and kit/auth/bun nothing). bun run check:install installs the packed package without the optional peers and checks that kit/access, kit/auth/rules and kit/auth/expo load and type-check there.
Bun only: bun install, bun run test, bun run typecheck (bun check), bun run format (bun fmt), bun run build (one ESM file per export, plus .d.ts types), bun run check:package, bun run check:install.
kit/admin: bun run playground (every component with sample data, http://127.0.0.1:4400), bun run test:e2e (axe in light and dark, phone width and behaviour, against the playground), bun run screenshots.
kit/tokens and kit/ui: the playground's /ui page shows every component in five themes (?theme=, ?scheme=, ?long=1 for labels as long as translations run, ?view=themes for all five side by side); bun run check:size holds the size budgets; bun run screenshots:ui takes the review screenshots. kit/ui/overlays: the playground's /overlays page opens each overlay the lazy way; bun run screenshots:overlays. Before working with UI SDK, read its official skill (.claude/skills/ui-sdk, restored with bunx skills install).
A new module goes in src/<name>.ts (or src/<group>/<name>.ts) with its test next to it. It gets its own subpath in package.json's exports (./<name> pointing at ./dist/<name>.js and ./dist/<name>.d.ts), and its allowed imports in IMPORTS in scripts/check-package.ts. A library it needs is an optional peer dependency, unless every module needs it.
The showcase (showcase/): the public site that shows kit/tokens and kit/ui live, in every theme. It is a static site built from the playground's own specimens: bun run build:showcase renders each page to HTML with its SEO tags, writes sitemap.xml, robots.txt, 404.html and a _headers file with the Content-Security-Policy into showcase/dist, and checks its size budget; bun run showcase builds and serves it as its host will (http://127.0.0.1:4402); bun run screenshots:showcase takes the review screenshots; bun run showcase:og redraws the share image (showcase/public/og.png) after the look changes. Settings come from the environment: SHOWCASE_ORIGIN (the site's address) and CF_BEACON_TOKEN (a Cloudflare Web Analytics token; without it no analytics script is added). Only invented theme names appear on it.
How the showcase is deployed: it is a Cloudflare Worker with static assets only (showcase/wrangler.jsonc), built and deployed by Cloudflare's Git integration (Workers Builds), not from this repository's workflows, so no Cloudflare token is stored here. It shows what is on npm, not what is on main: .github/workflows/showcase.yml moves the showcase branch to a release's tag when the release is published (or by hand, for any tag), and Cloudflare deploys that branch. Every other branch gets a preview address, built with the same commands and kept out of search engines (robots.txt, X-Robots-Tag) and out of the analytics. The build's settings in Cloudflare:
| Setting | Value |
|---|---|
| Production branch | showcase |
| Root directory | / |
| Build command | bun run build:showcase |
| Deploy command | bunx --bun wrangler@4.170.0 deploy --config showcase/wrangler.jsonc |
| Non-production branch deploy command | bunx --bun wrangler@4.170.0 versions upload --config showcase/wrangler.jsonc |
| Variables | CF_BEACON_TOKEN (the Web Analytics site token; it is public, it sits in the page), WRANGLER_SEND_METRICS=false |
Bun's version comes from packageManager in package.json. Wrangler is pinned in the commands rather than installed here, so this package's own installs stay small; raise it by hand.
Every release from 0.1.1 on comes from GitHub, with provenance. GitHub Actions publishes (.github/workflows/publish.yml) when a GitHub release is published for the tag vX.Y.Z matching package.json's version, after the run is approved in the npm environment. It uses npm's trusted publishing (OIDC): no npm token is stored anywhere, and npm attaches a provenance statement that links each version to the commit and workflow that built it (check it on the package's npm page, or with npm audit signatures). A stable version moves the latest tag; a prerelease (1.2.0-beta.1) goes to next.
0.1.0, the first version, was published by hand: npm only lets a trusted publisher be set up on a package that already exists. It has no provenance; its code is the same as 0.1.1's.
Versions follow semver. A breaking change to any module is a new major version.