Sign-in where the unsafe options don't exist.
One useOidc call signs users in with Google, Keycloak, Auth0, Entra or any OpenID Connect provider, on the web and, from the same source, on iOS and Android. Sessions, passkeys, TOTP, attempt limiting and an open-redirect-proof guard come with it, all on Web Crypto and fetch.
next release@pyreon/auth is on main; it is not on npm and is not part of the 1.0 release
Documentation- availability
- next releaseOn
maintoday; not on npm and not part of the 1.0 release. - tested against
oidc-providerA certified OpenID Provider, run in-process by the interop suite.- runs on
- browsers, Node, Bun, workerdWeb Crypto and
fetch, nothing else. - native
- iOS and Android, experimentalSystem browser sign-in; session in the Keychain or Keystore.
The code you least want to write yourself.
Secure defaults you can't turn downnext release
Authorization code with S256 PKCE,
stateandnonce, the RFC 9207 issuer check, https-only endpoints, single-use flows that expire in ten minutes. The implicit flow, the password grant and PKCEplainare not offered at all.No callback handler to writenext release
On the redirect page
useOidcscrubs the code from the address bar and history, checksstatein constant time, exchanges the code and verifies the ID token.status()readssignedInonly after the signature and nonce check out.One call, three platformsnext release
The same
useOidccompiles toASWebAuthenticationSessionon iOS and a Custom Tab on Android, with the session in the Keychain or Keystore.status()strings anderror()codes are identical on all three, and a shared set of signed test tokens must get the same verdict from the web, Swift and Kotlin verifiers.The rest of a login, server sidenext release
HMAC-signed
__Host-session cookies with secret rotation and revocation, RFC 6238 TOTP with replay protection, WebAuthn passkeys (ES256, and RS256 for Windows Hello), and a bounded attempt limiter.
The whole web integration.
A server route holding a client secret, a session provider around the app, and a hook with a loading state.
// pages/api/auth/[...nextauth].ts
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID ?? '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? '',
}),
],
})
// pages/_app.tsx wraps the app in <SessionProvider session={pageProps.session}>
// components/Account.tsx
import { signIn, signOut, useSession } from 'next-auth/react'
export function Account() {
const { data: session, status } = useSession()
if (status === 'loading') return null
return session ? (
<>
<p>Signed in as {session.user?.email}</p>
<button onClick={() => signOut()}>Sign out</button>
</>
) : (
<button onClick={() => signIn('google')}>Sign in</button>
)
}A public client with PKCE: no server route, no secret in your app. The redirect page completes the sign-in by itself.
import { useOidc } from '@pyreon/auth'
import { Show } from '@pyreon/core'
const auth = useOidc({
issuer: 'https://accounts.google.com',
clientId: 'your-client-id.apps.googleusercontent.com',
redirectUri: 'https://app.example.com/callback',
})
function Account() {
return (
<Show
when={() => auth.isAuthenticated()}
fallback={<button onClick={() => auth.signIn()}>Sign in</button>}
>
<p>Signed in as {() => auth.claim('email')}</p>
<button onClick={() => auth.signOut()}>Sign out</button>
</Show>
)
}Coming from Auth.js (next-auth) or Clerk?
From a server route and a session provider to one call.
// pages/api/auth/[...nextauth].ts
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID ?? '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? '',
}),
],
})
// pages/_app.tsx wraps the app in <SessionProvider session={pageProps.session}>
// components/Account.tsx
import { signIn, signOut, useSession } from 'next-auth/react'
export function Account() {
const { data: session, status } = useSession()
if (status === 'loading') return null
return session ? (
<>
<p>Signed in as {session.user?.email}</p>
<button onClick={() => signOut()}>Sign out</button>
</>
) : (
<button onClick={() => signIn('google')}>Sign in</button>
)
}Different shapes: Auth.js keeps the session on your server with a client secret; useOidc is a public client with PKCE. Want a server session too? createAuth with a shared FlowStore plus signSession is the backend-for-frontend version.
import { useOidc } from '@pyreon/auth'
import { Show } from '@pyreon/core'
const auth = useOidc({
issuer: 'https://accounts.google.com',
clientId: 'your-client-id.apps.googleusercontent.com',
redirectUri: 'https://app.example.com/callback',
})
function Account() {
return (
<Show
when={() => auth.isAuthenticated()}
fallback={<button onClick={() => auth.signIn()}>Sign in</button>}
>
<p>Signed in as {() => auth.claim('email')}</p>
<button onClick={() => auth.signOut()}>Sign out</button>
</Show>
)
}Keep the components, bring your own provider.
import { ClerkProvider, Show, SignInButton, UserButton, useUser } from '@clerk/react'
export function App() {
return (
<ClerkProvider publishableKey={PUBLISHABLE_KEY}>
<Account />
</ClerkProvider>
)
}
function Account() {
const { user } = useUser()
return (
<>
<Show when="signed-in">
<p>Signed in as {user?.primaryEmailAddress?.emailAddress}</p>
<UserButton />
</Show>
<Show when="signed-out">
<SignInButton />
</Show>
</>
)
}Clerk is a hosted user service with its own sign-in UI. @pyreon/auth is a library: you choose the identity provider (Keycloak, Auth0, Zitadel, Entra, Google) and own the screens.
import { useOidc } from '@pyreon/auth'
import { Show } from '@pyreon/core'
const auth = useOidc({
issuer: 'https://accounts.google.com',
clientId: 'your-client-id.apps.googleusercontent.com',
redirectUri: 'https://app.example.com/callback',
})
function Account() {
return (
<Show
when={() => auth.isAuthenticated()}
fallback={<button onClick={() => auth.signIn()}>Sign in</button>}
>
<p>Signed in as {() => auth.claim('email')}</p>
<button onClick={() => auth.signOut()}>Sign out</button>
</Show>
)
}Sign in, then try to break it.
This runs the real useOidc against an OpenID provider living inside the page. Sign in normally, then switch the provider into a misbehaving mode and sign in again: a replayed token, a forged signature, an issuer mix-up. Each one is stopped by a named check.
You are signed out.
- Discover the providerhttps only; the issuer must match the URL it came from
- Start the flowS256 PKCE challenge, random state and nonce; expires in 10 minutes
- Send the user to the providersystem browser on iOS and Android, a redirect on the web
- Check the callbackstate matches, iss matches (RFC 9207), flow used once
- Exchange the codewith the PKCE verifier, over https
- Verify the ID tokenRS256 or ES256 against the provider keys; nonce matches
- Signed inclaims verified; status() is signedIn
@pyreon/auth is Experimental. This runs it against an OpenID provider inside this page; only the network and the login page are simulated.
Authentication, end to end.
useOidcnext release reactive sign-in:status(),subject(),claim(name),accessToken(),expiresAt(),error(),refresh(),signOut().createAuthnext release the same state machine with every dependency explicit, for servers and backends-for-frontends with a sharedFlowStore.- Refresh that can't switch usersnext release a refreshed ID token must name the same
sub, or the session is cleared withsubject_changed. - Key rotation without restartsnext release
createJwksCacherefetches the provider's keys once when a token names an unknownkid. - Provider presetsnext release
google,keycloak(base, realm), and OAuth2 metadata forgithub,facebook()or anyoauth2(…)provider. - Signed sessionsnext release
signSession/verifySession/sessionCookie: HMAC-SHA-256, secrets of 32+ characters,isRevokedfor logout-everywhere. - TOTPnext release
generateTotpSecret,totp,verifyTotpwith ±1 step and alastUsedStepso a code works once. - Passkeysnext release
verifyRegistrationandverifyAssertion; user verification on by default, a non-increasingsignCountrejected. createAttemptLimiternext release per-key windows, bounded memory, and a flood of new keys can't buy a blocked key a fresh budget.createGuard+safeReturnTonext release route guards whosereturnTois checked with the browser's own URL parser, so//evil.exampleand tab tricks go home.
Things to build with it.
Throttle the guess, check the authenticator code once, and hand the browser a signed __Host- cookie instead of tokens.
import { createAttemptLimiter, sessionCookie, signSession, verifySession, verifyTotp } from '@pyreon/auth'
const revoked = new Set<string>()
const lastTotpStep = new Map<string, number>() // keep it on the user record in practice
const opts = {
secrets: [process.env.SESSION_SECRET ?? ''], // ≥ 32 characters; prepend a new one to rotate
maxAge: 8 * 60 * 60,
isRevoked: (jti: string) => revoked.has(jti),
}
const limiter = createAttemptLimiter({ max: 5, windowMs: 15 * 60_000 })
// after the password step: check the authenticator code, then issue the cookie
async function secondFactor(user: { id: string; totpSecret: string }, code: string) {
if (!limiter.attempt(user.id).allowed) return new Response('Try again later', { status: 429 })
const r = await verifyTotp(user.totpSecret, code, { lastUsedStep: lastTotpStep.get(user.id) })
if (!r.ok) return new Response('Wrong code', { status: 401 })
lastTotpStep.set(user.id, r.step) // the same code cannot pass a second time
limiter.reset(user.id)
const value = await signSession({ sub: user.id }, opts)
return new Response(null, { status: 303, headers: { location: '/', 'set-cookie': sessionCookie('session', value, opts.maxAge) } })
}
const whoIs = async (cookieValue: string) => (await verifySession(cookieValue, opts))?.sub ?? nullcreateGuard returns true or a login redirect carrying a safe returnTo.
import { createGuard, safeReturnTo } from '@pyreon/auth'
const requireAdmin = createGuard({
session: () => (auth.isAuthenticated() ? { role: auth.claim('role') } : null),
loginPath: '/login',
allow: (s) => s.role === 'admin',
})
requireAdmin('/admin/users') // true, or { redirect: '/login?returnTo=%2Fadmin%2Fusers' }
// after sign-in: go back, but only to a path on this origin
safeReturnTo('/admin/users') // '/admin/users'
safeReturnTo('//evil.example') // '/'
safeReturnTo('/\t/evil.example') // '/'The bearer header is built inside queryFn, and the user is part of the key, so signing in as someone else refetches.
import { useOidc } from '@pyreon/auth'
import { Text } from '@pyreon/primitives'
import { useQuery } from '@pyreon/query'
type Me = { name: string; email: string }
function Account() {
const auth = useOidc({
issuer: 'https://accounts.example.com',
clientId: 'app',
redirectUri: 'https://app.example.com/callback',
nativeRedirectUri: 'com.example.app:/oauth',
})
const me = useQuery<Me>(() => ({
queryKey: ['me', auth.subject() ?? 'anonymous'], // a new user refetches
queryFn: () =>
fetch('https://api.example.com/me', {
headers: { authorization: `Bearer ${auth.accessToken() ?? ''}` },
}).then((r) => r.json()),
enabled: auth.isAuthenticated(),
}))
return <Text>{me.data()?.name ?? auth.status()}</Text>
}Everything the docs cover, from one import.
Every export has a reference page with its signature, an example and the mistakes people make with it.
- useOidc
- createAuth
- memoryFlowStore
- sessionStorageFlowStore
- AuthError
- discover
- beginAuthorization
- parseCallback
- exchangeCode
- refreshTokens
- endSessionUrl
- verifyIdToken
- createJwksCache
- fetchJwks
- tokenKid
- keycloak
- github
- oauth2
- withPreset
- signSession
- verifySession
- sessionCookie
- createGuard
- safeReturnTo
- createAttemptLimiter
- generateTotpSecret
- totp
- verifyTotp
- passkeyChallenge
- verifyRegistration
- verifyAssertion
- @pyreon/auth/passport
- @pyreon/auth/native-plugin
Good to know before you start.
A web reload starts signed out, on purpose
Browser tokens live in memory, never in localStorage, so one XSS bug can't steal a long-lived session. To stay signed in, call signIn() on load (the provider usually answers without a prompt) or keep the session on your server with signSession.
Several servers need a shared flow store
Pending sign-ins live in one process by default. Implement FlowStore over Redis or similar, with an atomic take.
GitHub and Facebook are OAuth2, not OIDC
There is no verified identity to read, so use createAuth with their metadata and fetch the user from their API.
Android needs two manifest entries
Declare PyreonAuthActivity and PyreonAuthRedirectActivity with your redirect scheme. iOS needs no setup for sign-in.
What people ask first.
Can I install it today?
It is on main and is not part of the 1.0 release; the npm latest does not include it. Everything on this page describes main.
Is it a hosted service?
No. It is a library. Your identity provider (Google, Keycloak, Auth0, Okta, Zitadel, Entra, anything that speaks OpenID Connect) holds the users; the package does the protocol and the checks.
How do I know the checks work?
The interop suite runs against oidc-provider, a certified OpenID Provider, in-process. The web, Swift and Kotlin verifiers judge one shared file of signed test tokens and must agree down to the error code. The demo above shows three attacks being refused, each by a named check.
Where do tokens live?
On the web, in memory only. On iOS and Android, in the Keychain or Keystore, so the app stays signed in after a relaunch and refreshes an expired session on launch.
Does it do passwords?
No password storage or hashing. It covers the sign-in protocol, sessions, second factors and passkeys; password sign-in belongs to your identity provider.
Built to be used together.
Sign-in, minus the afternoon of reading RFCs. We read them.
next release@pyreon/auth is on main; it is not on npm and is not part of the 1.0 release
Read the auth guide