Autonomous Execution

© 2026 HY13dev™. All Rights Reserved.
Get in touch
HY13dev Logo
HomeHome
Projects Icon
ProjectsProjects
Education Icon
EducationEducation
Experience Icon
ExperienceExperience
Contact Icon
ContactContact
YlyaBot Icon
YlyaBotYlyaBot
Ylya Martchenko
2026
Back to Projects
Full Stack Developer•Senior Software Engineer•Next.js & React Expert•GenAI & RAG Systems Engineer•Full Stack Developer•Senior Software Engineer•Next.js & React Expert•GenAI & RAG Systems Engineer•

HY13 Passkey SSO

Lead Full-Stack Security & Identity EngineerProduction
Live Sync

🔐 Lightweight, self-hosted OpenID Connect (OIDC) identity provider for first & third-party apps. Features passwordless auth (passkeys & magic links), PKCE, consent gates, and per-app roles. Built with Next.js 16, Bun, Prisma, and Redis.

Project Overview

A small, self-hosted OpenID Connect identity provider — a 'mini-Keycloak' — that centralizes authentication for first- and third-party applications. Users authenticate with a passkey (WebAuthn) or by email, either opening a magic link or typing the 6-digit code sent with it, then are redirected back to the calling app with standard OIDC tokens whose access token carries their identity and per-app roles. It implements the full standards-compliant Authorization Code + PKCE (S256) flow with RS256-signed, self-contained access/ID tokens, a discovery document and JWKS endpoint, rotating refresh tokens with replay (reuse) detection, the prompt parameter (none, login, consent, select_account), RP-initiated and OIDC Back-Channel Logout, ui_locales, a consent screen for third-party apps and an account confirmation for trusted ones, and a per-client role-based access-control model administered from a built-in dashboard. New accounts are offered a passkey right after sign-up, and accounts without one are reminded once a day, with a no_passkey claim so apps can nudge their users too. Users manage their profile (username, names, birthday, photo), passkeys, sign-in sessions and linked apps from an account page that links back to the app they came from, and get an email in their language whenever a passkey is added to or removed from their account. They can move their account to a new email address after proving it's them (with a passkey, or a code to the current address) and confirming the new address with a code sent to it; the old address is told. Sign-ins from a device the account hasn't used before email the owner with the device and the app it was for, code emails name the app they sign in to, and users can delete their account themselves: after the same confirmation they are signed out everywhere, the account is deleted 30 days later by the daily cron, and signing in before then cancels it. Built on Next.js 16 (App Router with cacheComponents/PPR and the React 19 compiler) on bun, it uses Prisma 7 over PostgreSQL (Neon) through the @prisma/adapter-pg driver adapter with UUIDv7 identifiers for durable state, and Upstash Redis (with TTLs) for ephemeral state — WebAuthn challenges, magic-link tokens and codes, and short-lived OIDC authorization codes — so the database holds only durable rows. Emails are sent with Resend, sign-in is shielded by Upstash Redis rate limiting and Cloudflare Turnstile, and the whole stack runs at $0/month on free tiers. It is not a toy: it is the live identity provider behind a separate Confluence-RAG product, issuing the role-bearing access tokens that an MCP server verifies for RBAC, and behind Werewolves, a multiplayer game app whose players sign in from browsers and installed iPhone apps.

View on GitHubOpen Live Demo

Specifications

  • My RoleLead Full-Stack Security & Identity Engineer
  • Development PhaseProduction
  • Languages
    TypeScriptJavaScriptSQLHTMLCSS
  • Tools & Frameworks
    Next.js 16 (App Router, cacheComponents / PPR)React 19 (React Compiler)Prisma 7 ORM (driver adapters)PostgreSQL (Neon)jose (RS256 / JWKS)SimpleWebAuthn (WebAuthn / passkeys)

Execution Latency

Short-lived, self-contained RS256 access/ID tokens (15 min TTL by default) verifiable offline against the JWKS with no introspection round-trip; refresh tokens valid 30 days with rotation on every use; OIDC authorization codes live 60 seconds in Redis, WebAuthn challenges 5 minutes, magic links and their codes 15 minutes; sliding-window Redis rate limiting adds single-digit-millisecond overhead per auth action.

UI Performance

Next.js 16 cacheComponents (Partial Prerendering) streams dynamic, cookie-dependent sections while static shells prerender instantly, and the React 19 compiler removes manual memoization; every press answers at once: profile edits, passkey renames and removals of passkeys, sessions and linked apps show their result immediately and roll back with an error toast if the server refuses, then router.refresh() re-streams authoritative state; adding a passkey stays pessimistic because it waits on the authenticator. Once a passkey answers, the sign-in form gives way to an animated fingerprint (with a way back) while the server checks it and the next page loads, so the email field never looks usable mid-sign-in. Destructive actions confirm in styled dialogs rather than the browser's own, a sign-in for an app shows a fixed 'Back to {app}' link to the app's registered home page, nothing on the page shifts as streamed parts arrive, spinners that run until a page leaves reset when the Back button restores it from memory, and an EN/FR switch on every page keeps the app's return address and brings the sign-in form back to its step (typed email, or the code screen while the code is valid). Leaving the profile with unsaved changes asks first (save and leave, leave without saving, or stay), with the browser's own warning for reloads and closed tabs; all surfaced through accessible Radix modals and Sonner toasts.

Engineering Highlights & Achievements

1

Standards-Compliant OIDC Authorization Server: Implemented the full OpenID Connect Authorization Code + PKCE (S256-only) flow from scratch with jose — discovery document, JWKS endpoint, RS256-signed self-contained access and ID tokens (identity claims + per-audience `roles` + an `admin` boolean), UserInfo, the `prompt` parameter, `ui_locales`, RP-initiated logout and Back-Channel Logout — with CORS on the token and UserInfo endpoints for public browser clients, so any off-the-shelf OIDC client library integrates without custom glue.

2

Refresh-Token Rotation with Reuse Detection: Engineered a rotating refresh-token family model (hashed tokens, family id, used/revoked flags) where presenting an already-rotated token is treated as a replay and revokes the entire token family. A 10-second grace window gives a legitimate client that refreshes twice at once (two tabs, a retried request) a successor in the same family instead of a lockout, and ending a sign-in session revokes every app token it issued.

3

Passwordless Identity: Built dual passwordless auth — SimpleWebAuthn passkeys (platform authenticators, signature verification, per-credential management) plus email sign-in, where each email carries a single-use magic link and a 6-digit code (hashed in Redis, five tries, only the newest one valid) — backed by DB-stored, httpOnly, individually revocable login sessions. Opening a link only shows a confirmation page and the sign-in happens on its POST, so mail scanners that prefetch every link can't burn the token; sign-ins started from an app get a code-only email, because an installed iPhone web app never receives links.

Engineering Challenges (STAR Method)

Exhaustive situation-action-result breakdowns showcasing problem-solving and architectural execution.

CHALLENGE 1

Situation & Impediment

Long-lived refresh tokens are the highest-value secret an identity provider holds: if one is exfiltrated, an attacker can silently mint access tokens indefinitely, and naive rotation schemes still let a stolen token be replayed once.

Engineering Action

Modeled refresh tokens as rotating families — each token is stored only as a SHA-256 hash with a family id, expiry, and used/revoked flags. On every refresh the presented token is rotated to a fresh one; if a token that has already been rotated (used) is ever presented again, it is treated as a replay and the entire family is revoked in a single transaction, logging the legitimate user out everywhere.

Architectural Deep Dive

Low-level component relationships, system boundaries, and runtime flows.

State is deliberately split by lifetime. Durable identity data — users, WebAuthn credentials, registered clients, app memberships (consent links), rotating refresh tokens, and login sessions — lives in PostgreSQL (Neon) with UUIDv7 primary keys, accessed through Prisma 7's @prisma/adapter-pg driver adapter (pooled URL for reads, a direct URL for migrations). Ephemeral, security-sensitive state — WebAuthn challenges, magic-link tokens and their hashed 6-digit codes, and OIDC authorization codes (bound to the PKCE challenge, user, client, nonce, scope and session) — lives only in Upstash Redis with TTLs, so it self-expires and never pollutes the database. The OIDC surface is a set of App Router route handlers: /api/oidc/authorize validates client, redirect_uri, PKCE, scope, state, nonce and prompt, then requires a login session (redirecting to sign-in with a return path and the requested language), requires a completed username, offers a passkey once a day, and asks for consent (third-party clients) or an account confirmation (trusted clients the account hasn't used yet, unless it just signed in) before minting a short-lived authorization code; native clients with custom-scheme redirect URIs get a hand-off page instead of a bare redirect. /api/oidc/token exchanges that code (verifying the PKCE code_verifier) for RS256 access/ID/refresh tokens or rotates a refresh token; /api/oidc/userinfo and /api/oidc/logout complete the standard set, back-channel logout tokens go to registered apps when a session ends, and discovery and JWKS are exposed under /.well-known via rewrites. RS256 keys are loaded from base64-encoded PEM in the environment, and the ISSUER env both signs tokens and builds endpoint URLs. The web app runs on Next.js 16 with cacheComponents (Partial Prerendering): authorization guards live inside each page (not layouts) so static shells prerender while authenticated, cookie-dependent reads stream within the dynamic boundary, and a proxy handles locale prefixes, signed-in redirects and the daily passkey check. Sign-in actions are protected by Upstash rate limiting and Cloudflare Turnstile, and a daily GitHub Actions cron hits /api/cron to keep the data stores warm and purge stale rows.

Lessons Learned & Core Takeaways

Building a standards-compliant OpenID Connect provider from primitives — jose for RS256/JWKS, SimpleWebAuthn for passkeys, Redis for ephemeral code/token state — made the security model concrete in a way that adopting a black-box auth SaaS never does: PKCE binding, refresh rotation with reuse detection, and audience-scoped role claims stop being buzzwords and become code you can reason about and test. Next.js 16's cacheComponents also reframed authorization as a data-fetching concern rather than a routing one: guards belong at the page/data boundary, not in layouts, because Partial Prerendering will happily stream a child page that a layout redirect was supposed to block; and a cookie set by a server action re-renders the page, which can quietly undo a redirect, so side effects that must not re-render belong in the proxy. Real client apps were the best test: an installed iPhone web app that never receives links, two tabs refreshing at once, and mail scanners opening every link each exposed an assumption that a spec-compliant flow alone didn't cover. Finally, separating durable state (Postgres, UUIDv7) from ephemeral state (Redis with TTLs) and automating keep-warm plus cleanup proved you can run a genuinely production-grade, multi-tenant identity provider — one that real third-party apps depend on — at zero monthly cost without compromising on the security guarantees that matter.

Live Interactive Preview

Rendered live in real-time. Direct URL: https://auth.hy13dev.com

If the preview remains blank, the site's security policies may restrict iframe embedding. Open the link directly instead.
https://auth.hy13dev.com
Upstash Redis
Resend API
Cloudflare Turnstile
Tailwind CSS v4
Radix UI
Zod
bun
  • Stars0
  • Forks0
  • Last Updated11/11/2026
  • Operational Cost

    $0/month runtime on free tiers — Neon PostgreSQL (pooled + direct/migration URLs), Upstash Redis, Resend, Cloudflare Turnstile, and Vercel — kept warm and clean by a daily GitHub Actions cron.

    4

    OIDC Back-Channel Logout: When a sign-in session ends (signing out, revoking a session or a device), every app it signed into gets a signed logout token at its registered back-channel URI, with the session id (`sid`) so the app ends only that sign-in, and the app's refresh tokens are revoked so it can't quietly mint new access tokens. The other way round, a confidential app can end a sign-in from its own server, authenticated by its client secret and the refresh token that sign-in issued (advertised in discovery as `server_end_session_endpoint`), so its users sign out instantly without a redirect through the identity provider, and the provider's own session ends with it. When an account is deleted, the provider keeps a 90-day tombstone per app that knew it (`deleted_accounts_endpoint`), so each app can delete that person's data on its own schedule, and a missed run catches up.

    5

    Passkey Adoption Built Into the Flow: New accounts are offered a passkey right after choosing a username, and accounts without one are offered it at most once a day, on any page or on the way into an app, tracked with a cookie set by the proxy so the prompt never fights the page it leads back to. Tokens carry a `no_passkey` claim so client apps can remind their own users.

    6

    No Surprise QR Codes: Browsers can't tell a site whether a device holds a passkey, so a 'Continue with passkey' button on a device without one opens another device's QR code, which confuses people who never set one up. The sign-in page has no passkey button: the email field offers this device's passkeys (synced ones included) in its autofill through WebAuthn conditional mediation, so picking one and confirming with biometrics signs in, and a device without any simply shows nothing; the field is focused on load, so some desktop browsers show the suggestion without a click. When someone asks for an email code for an account that has passkeys, the page offers them first with a prompt limited to that account's own passkeys, so a device holding one uses it at once and only a device without any offers the phone's QR code. That offer always leaves a way out: 'Email me a code instead' or 'Use another email'. Preparing the autofill on every page view uses its own rate-limit bucket, so loading the page never uses up sign-in attempts.

    7

    Per-Client RBAC with Env-Driven Admin: Designed a per-application role model — each registered client defines its own role palette and a `defaultRoles` set auto-assigned on first link — assigned from an admin dashboard, while the privileged `admin` flag is computed from an `ADMIN_EMAIL` env value rather than stored, so rotating the env rotates super-admin with zero database writes.

    8

    Free-Tier Operational Hardening: Split state across PostgreSQL (durable, UUIDv7) and Upstash Redis (ephemeral, TTL-bound challenges/codes/tokens), guarded actions with Redis rate limiting and Turnstile, and added an authorized /api/cron endpoint (daily via GitHub Actions) that keep-warms Postgres + Redis against cold starts and transactionally purges abandoned signups, expired sessions, and expired refresh tokens.

    Quantifiable Result

    Bounded the blast radius of a stolen refresh token to a single use and a forced re-authentication, achieving Keycloak/Auth0-grade reuse-detection semantics on a self-hosted, zero-cost stack, verified end-to-end by an automated reuse-detection check.

    CHALLENGE 2

    Situation & Impediment

    Next.js 16's cacheComponents (Partial Prerendering) changes how authentication guards behave: a redirect() in a layout does not reliably halt rendering or data fetching in the child page, so a protected page could still execute its queries and stream privileged data before the redirect lands.

    Engineering Action

    Moved every authorization guard out of shared layouts and into each protected page, checking the session and required state (verified email, completed username, admin identity) before any data fetch, and kept ephemeral/cookie-dependent reads inside the dynamic boundary so the static shell can still prerender.

    Quantifiable Result

    Eliminated the data-leak window entirely while preserving Partial Prerendering's instant static shells — protected pages never touch the database until the request is proven authorized.

    CHALLENGE 3

    Situation & Impediment

    An identity provider needs to serve real third-party applications, not just a demo login form — those apps must be able to register, receive role-scoped tokens, and trust the issuer with any standard OIDC client.

    Engineering Action

    Built an admin dashboard to register clients (redirect URIs, post-logout URIs, trusted flag, per-app role palette, default roles, optional hashed client secret) and assign user roles, then wired the issuer to embed each client's resolved roles into the audience-scoped access token; integrated it as the live SSO for a separate Confluence-RAG product where a Tauri desktop client signs in via PKCE and an MCP server verifies the role-bearing access token (alongside legacy pre-shared tokens) for RBAC.

    Quantifiable Result

    Turned the project from a template into a production identity provider with a real downstream consumer — one user account, role-aware tokens, and a standards-based integration surface that any OIDC library can consume.

    CHALLENGE 4

    Situation & Impediment

    Deploying a stateful auth stack entirely on free tiers invites Neon PostgreSQL cold starts after idle periods, database pollution from abandoned magic-link signups, and unbounded growth of expired sessions and refresh tokens.

    Engineering Action

    Added an /api/cron endpoint guarded by a Bearer CRON_SECRET and driven by a daily GitHub Actions workflow that pings Postgres and Redis to keep them warm, then runs a single transaction deleting unconfirmed users (no username and no passkey older than 24h), expired login sessions, and expired refresh tokens.

    Quantifiable Result

    Eliminated cold starts on the critical login path and automated 100% of stale-row cleanup, keeping a lean schema and predictable latency at zero infrastructure cost.

    CHALLENGE 5

    Situation & Impediment

    Players of a game app signed in from its installed iPhone home-screen app, but tapping the magic link in their email opened Safari instead, which keeps separate cookies: Safari got signed in, the app never did, and new accounts were left on the identity provider's account page instead of going back to the app.

    Engineering Action

    Added a 6-digit code to every sign-in email, typed on the sign-in page so the session lands wherever the sign-in started, and made emails for sign-ins coming from an app code-only. Traced the lost redirect to Next.js re-rendering the page after a server action set a cookie (which on iOS dropped the return address), and moved that cookie to the proxy so no page re-renders on the way back.

    Quantifiable Result

    Sign-up and sign-in from an installed iPhone app now go through and land back in the app, with a passkey offered on the way, verified on the device that had failed.

    CHALLENGE 6

    Situation & Impediment

    With refresh-token reuse detection in place, a legitimate client could lock itself out: two tabs, or a retried request after a network blip, presenting the same refresh token within milliseconds looked exactly like a stolen-token replay and revoked the whole family.

    Engineering Action

    Added a 10-second grace window: a token reused within it, or a second request that loses the race to claim it atomically, gets a fresh successor in the same family instead of triggering revocation, while any reuse after the window still revokes everything.

    Quantifiable Result

    Concurrent refreshes no longer sign users out, and replay detection keeps its guarantee for anything outside a few seconds of the legitimate rotation.