Skip to content
@pyreon/auth
fundamentals · authentication

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 main today; 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.
useOidc signs in through PKCE, state, nonce and token checks auth.signIn() runs five steps: authorization request with S256 PKCE, state and nonce; the provider sign-in; the callback, where the code is scrubbed from the address bar and state is checked; the code exchange; and ID-token verification of signature, nonce and issuer. auth.status() moves from signedOut to signingIn to signedIn only after the last check. A side panel lists what is not offered at all: the implicit flow, the password grant and PKCE plain. @PYREON/AUTH · USEOIDC · ONE SIGN-IN authorize S256 PKCE · state · nonce ✓ provider sign-in https-only issuer ✓ callback code scrubbed · state checked ✓ exchange code single-use, 10 min ✓ verify ID token signature · nonce · iss ✓ auth.status() 'signedOut' 'signingIn' 'signedIn' only after every check not offered at all implicit flow password grant PKCE 'plain' the same call on iOS and Android (experimental)
why teams pick it

The code you least want to write yourself.

  1. Secure defaults you can't turn downnext release

    Authorization code with S256 PKCE, state and nonce, the RFC 9207 issuer check, https-only endpoints, single-use flows that expire in ten minutes. The implicit flow, the password grant and PKCE plain are not offered at all.

  2. No callback handler to writenext release

    On the redirect page useOidc scrubs the code from the address bar and history, checks state in constant time, exchanges the code and verifies the ID token. status() reads signedIn only after the signature and nonce check out.

  3. One call, three platformsnext release

    The same useOidc compiles to ASWebAuthenticationSession on iOS and a Custom Tab on Android, with the session in the Keychain or Keystore. status() strings and error() 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.

  4. 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 difference

The whole web integration.

Auth.js (next-auth 4) in Next.js

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>
  )
}
with @pyreon/auth

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

Coming from Auth.js (next-auth) or Clerk?

From a server route and a session provider to one call.

Auth.js (next-auth)
// 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>
  )
}
Pyreon

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.

Clerk
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>
    </>
  )
}
Pyreon

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>
  )
}
try it

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.

Acmesigned out

You are signed out.

Provider behaviour
what the package does
  1. Discover the providerhttps only; the issuer must match the URL it came from
  2. Start the flowS256 PKCE challenge, random state and nonce; expires in 10 minutes
  3. Send the user to the providersystem browser on iOS and Android, a redirect on the web
  4. Check the callbackstate matches, iss matches (RFC 9207), flow used once
  5. Exchange the codewith the PKCE verifier, over https
  6. Verify the ID tokenRS256 or ES256 against the provider keys; nonce matches
  7. Signed inclaims verified; status() is signedIn
experimental

@pyreon/auth is Experimental. This runs it against an OpenID provider inside this page; only the network and the login page are simulated.

what's included

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 shared FlowStore.
  • Refresh that can't switch usersnext release a refreshed ID token must name the same sub, or the session is cleared with subject_changed.
  • Key rotation without restartsnext release createJwksCache refetches the provider's keys once when a token names an unknown kid.
  • Provider presetsnext release google, keycloak(base, realm), and OAuth2 metadata for github, facebook() or any oauth2(…) provider.
  • Signed sessionsnext release signSession / verifySession / sessionCookie: HMAC-SHA-256, secrets of 32+ characters, isRevoked for logout-everywhere.
  • TOTPnext release generateTotpSecret, totp, verifyTotp with ±1 step and a lastUsedStep so a code works once.
  • Passkeysnext release verifyRegistration and verifyAssertion; user verification on by default, a non-increasing signCount rejected.
  • 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 whose returnTo is checked with the browser's own URL parser, so //evil.example and tab tricks go home.
recipes

Things to build with it.

next release
A second factor, then a session cookie

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 ?? null
next release
An admin route that can't be bounced off-site

createGuard 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') // '/'
next release
Call your API from web, iOS and Android

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>
}
api

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.

sign-in · 5
  • useOidc
  • createAuth
  • memoryFlowStore
  • sessionStorageFlowStore
  • AuthError
OIDC steps · 6
  • discover
  • beginAuthorization
  • parseCallback
  • exchangeCode
  • refreshTokens
  • endSessionUrl
ID tokens · 4
  • verifyIdToken
  • createJwksCache
  • fetchJwks
  • tokenKid
providers · 6
  • google
  • keycloak
  • github
  • facebook
  • oauth2
  • withPreset
sessions and guards · 6
  • signSession
  • verifySession
  • sessionCookie
  • createGuard
  • safeReturnTo
  • createAttemptLimiter
second factors · 6
  • generateTotpSecret
  • totp
  • verifyTotp
  • passkeyChallenge
  • verifyRegistration
  • verifyAssertion
subpaths · 2
  • @pyreon/auth/passport
  • @pyreon/auth/native-plugin
good to know

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.

questions

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.

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