惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
Spread Privacy
Spread Privacy
Cloudbric
Cloudbric
V
Vulnerabilities – Threatpost
博客园 - 叶小钗
I
Intezer
S
Secure Thoughts
Jina AI
Jina AI
T
Tenable Blog
博客园 - 【当耐特】
WordPress大学
WordPress大学
W
WeLiveSecurity
宝玉的分享
宝玉的分享
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Google DeepMind News
Google DeepMind News
Schneier on Security
Schneier on Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog RSS Feed
Martin Fowler
Martin Fowler
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
IT之家
IT之家
小众软件
小众软件
P
Privacy & Cybersecurity Law Blog
V
Visual Studio Blog
S
Securelist
M
MIT News - Artificial intelligence
H
Help Net Security
Scott Helme
Scott Helme
N
News and Events Feed by Topic
SecWiki News
SecWiki News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园_首页
Microsoft Azure Blog
Microsoft Azure Blog
P
Proofpoint News Feed
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
The Cloudflare Blog
T
Tailwind CSS Blog
A
About on SuperTechFans
The Last Watchdog
The Last Watchdog
S
Security @ Cisco Blogs
大猫的无限游戏
大猫的无限游戏
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
H
Heimdal Security Blog
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Persistent JWT Signing Keys with PostgreSQL
ShyGyver · 2026-04-27 · via DEV Community

The previous article ended with this caveat:

In production, replace createInMemoryKeyStore() with a persistent store backed by a database or secrets manager so keys survive restarts.

This article does exactly that. We'll swap the in-memory key store for two PostgreSQL-backed implementations:

  • A JwksKeyStore that stores private keys with envelope encryption (AES-256-GCM, DEK + KEK) and public keys as plain JSON.
  • A JwksRotationTimestampStore that derives the last rotation time directly from the key record's creation time.

Everything else in index.ts (the flow builder, endpoints, login form) stays identical.


TL;DR

The full runnable example is available at Github (oidc-persistent-app).


The problem with in-memory keys

createInMemoryKeyStore() keeps key material in process memory. This has two consequences in production:

Scenario What happens
Server restart A new key pair is generated. All tokens issued before the restart are now unverifiable
Multiple instances / pods Each instance generates its own key pair. Tokens verified by a different instance than the one that signed them will fail

The fix is straightforward: persist the key material to a shared store. Because private keys are sensitive, they must be stored encrypted.


Key concepts

@saurbit/oauth2-jwt defines two interfaces that JoseJwksAuthority and JwksRotator depend on:

JwksKeyStore manages key material:

interface JwksKeyStore {
  storeKeyPair(kid: string, privateKey: object, publicKey: object, ttl: number): Promise<void>;
  getPublicKeys(): Promise<object[]>;
  getPrivateKey(): Promise<object | undefined>;
}

Enter fullscreen mode Exit fullscreen mode

JwksRotationTimestampStore tracks when the last rotation occurred:

interface JwksRotationTimestampStore {
  getLastRotationTimestamp(): Promise<number>;
  setLastRotationTimestamp(timestamp: number): Promise<void>;
}

Enter fullscreen mode Exit fullscreen mode

In the in-memory version, createInMemoryKeyStore() returns a single object that satisfies both interfaces, so it can be passed for both jwksStore and rotationTimestampStore. For the persistent version we are going to make two separate objects, each backed by database queries.

Envelope encryption

Understanding DEK and KEK in Encryption: A Practical Guide.

Private keys MUST NEVER be stored in plaintext. This implementation uses an envelope encryption pattern:

  1. A fresh random DEK (Data Encryption Key, 256-bit) is generated for each key pair.
  2. The private key is serialized to JSON and encrypted with the DEK using AES-256-GCM.
  3. The DEK itself is wrapped (encrypted) with a master KEK loaded from the MASTER_KEY environment variable.
  4. The encrypted private key and the wrapped DEK are stored together in the database.

This means:

  • Even if the database is breached, the private keys are unreadable without the KEK.
  • The KEK lives only in the environment (or a secrets manager) and NEVER in the database.

Prerequisites

Start from the server built in the previous article. You need a PostgreSQL database (local, Neon, Supabase, etc.) and two environment variables:

Variable Description
DATABASE_URL PostgreSQL connection string
MASTER_KEY Base64-encoded 32-byte key (256 bits) used as the KEK

MASTER_KEY must be a base64-encoded 32-byte value. In a real deployment, store it in a secrets manager (AWS Secrets Manager, Vault, etc.) and inject it at runtime. Never commit it to source control.
You can generate a random Base64 of 32 bytes at Random Base64 String Generator.


Database schema

Create the two tables below. The private_keys table stores exactly one active row at a time enforced by UNIQUE (id) and CHECK (id = 1). Older private keys are overwritten on rotation, while public_keys accumulates all keys still within their TTL so that tokens signed with a previous key continue to verify until they expire.

CREATE TABLE IF NOT EXISTS private_keys
(
    key_id      character varying(255) NOT NULL,
    id          integer NOT NULL DEFAULT 1,
    private_key text NOT NULL,
    wrapped_dek text NOT NULL,
    expires_at  timestamp with time zone NOT NULL,
    created_at  timestamp with time zone NOT NULL DEFAULT now(),
    CONSTRAINT private_keys_pkey PRIMARY KEY (key_id),
    CONSTRAINT private_keys_id_unique UNIQUE (id),
    CONSTRAINT id CHECK (id = 1)
);

CREATE TABLE IF NOT EXISTS public_keys
(
    key_id     character varying(255) NOT NULL,
    public_key text NOT NULL,
    expires_at timestamp with time zone NOT NULL,
    created_at timestamp with time zone NOT NULL DEFAULT now(),
    CONSTRAINT public_keys_pkey PRIMARY KEY (key_id)
);

Enter fullscreen mode Exit fullscreen mode


Step 1: Install the PostgreSQL driver

bun add pg
bun add -d @types/pg

Enter fullscreen mode Exit fullscreen mode


Step 2: Write src/db.ts

This module owns all database access. It exposes typed interfaces and four query functions used by the stores.

import { Pool } from "pg";

const ENV_DATABASE_URL = process.env.DATABASE_URL;

const pool = new Pool({
  connectionString: ENV_DATABASE_URL,
  max: 10,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
  ssl: {
    rejectUnauthorized: false,
  },
});

export interface PrivateKeyRecord {
  keyId: string;
  privateKey: string;
  wrappedDek: string;
}

export interface PublicKeyRecord {
  keyId: string;
  publicKey: string;
}

Enter fullscreen mode Exit fullscreen mode

saveKeyPairRecord

Persists both keys inside a transaction. The ON CONFLICT (id) DO UPDATE clause on private_keys ensures the table always contains at most one row and new rotations overwrite the old private key in-place.

export async function saveKeyPairRecord(
  privateKey: PrivateKeyRecord,
  publicKey: PublicKeyRecord,
  expirationTime: number
) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const createdAt = Date.now();
    const queryPrivateKey = `
      INSERT INTO private_keys (id, key_id, private_key, wrapped_dek, expires_at, created_at)
      VALUES ($1, $2, $3, $4, to_timestamp($5::bigint / 1000), to_timestamp($6::bigint / 1000))
      ON CONFLICT (id)
      DO UPDATE SET
        key_id     = EXCLUDED.key_id,
        private_key = EXCLUDED.private_key,
        wrapped_dek = EXCLUDED.wrapped_dek,
        expires_at  = EXCLUDED.expires_at,
        created_at  = EXCLUDED.created_at
      RETURNING *;
    `;
    const queryPublicKey = `
      INSERT INTO public_keys (key_id, public_key, expires_at, created_at)
      VALUES ($1, $2, to_timestamp($3::bigint / 1000), to_timestamp($4::bigint / 1000))
    `;
    await client.query(queryPrivateKey, [
      1,
      privateKey.keyId,
      privateKey.privateKey,
      privateKey.wrappedDek,
      expirationTime,
      createdAt,
    ]);
    await client.query(queryPublicKey, [
      publicKey.keyId,
      publicKey.publicKey,
      expirationTime,
      createdAt,
    ]);
    await client.query("COMMIT");
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

Enter fullscreen mode Exit fullscreen mode

Read functions

export async function getPrivateKeyRecord(): Promise<PrivateKeyRecord | null> {
  const query = "SELECT * FROM private_keys WHERE expires_at > NOW() LIMIT 1";
  try {
    const res = await pool.query<{ key_id: string; private_key: string; wrapped_dek: string }>(
      query
    );
    if (res.rows.length > 0) {
      const row = res.rows[0];
      return {
        keyId: row.key_id,
        privateKey: row.private_key,
        wrappedDek: row.wrapped_dek,
      };
    }
  } catch (err) {
    console.error("Error fetching record:", err);
  }
  return null;
}

export async function getPublicKeyRecords(): Promise<PublicKeyRecord[] | null> {
  const query = "SELECT * FROM public_keys WHERE expires_at > NOW()";
  try {
    const { rows } = await pool.query<{ key_id: string; public_key: string }>(query);
    return rows.map((row) => ({ keyId: row.key_id, publicKey: row.public_key }));
  } catch (err) {
    console.error("Error fetching record:", err);
  }
  return null;
}

export async function getPrivateKeyCreatedAt(): Promise<Date | null> {
  const query = "SELECT created_at FROM private_keys WHERE expires_at > NOW() LIMIT 1";
  try {
    const { rows } = await pool.query<{ created_at: Date }>(query);
    if (rows.length > 0) {
      return rows[0].created_at;
    }
  } catch (err) {
    console.error("Error fetching record:", err);
  }
  return null;
}

Enter fullscreen mode Exit fullscreen mode

getPublicKeyRecords returns all rows where expires_at is in the future and not just the current key. This is intentional: resource servers need to verify tokens signed with the previous key during the overlap period after a rotation.


Step 3: Write src/stores.ts

This module implements the two interfaces (JwksKeyStore, JwksRotationTimestampStore). It imports the DB functions from db.ts and handles all the encryption logic.

Imports and master key

import {
  getPrivateKeyCreatedAt,
  getPrivateKeyRecord,
  getPublicKeyRecords,
  PrivateKeyRecord,
  PublicKeyRecord,
  saveKeyPairRecord,
} from "./db";
import { JwksKeyStore, JwksRotationTimestampStore } from "@saurbit/oauth2-jwt";

/**
 * In a production environment, the master key (KEK) should be stored securely,
 * such as in an environment variable or a secrets manager.
 * It should never be hardcoded in the source code.
 * This should be a base64-encoded 32-byte key (256 bits) for AES-256 encryption.
 */
const ENV_MASTER_KEY = process.env.MASTER_KEY!;

const MASTER_KEY_RAW = base64ToUint8Array(ENV_MASTER_KEY);

Enter fullscreen mode Exit fullscreen mode

Crypto helpers

Two small utilities (base64ToUint8Array, uint8ArrayToBase64) convert between Uint8Array and Base64 for storage, and two functions (decrypt, encrypt) wrap the Web Crypto API for AES-GCM encryption. The IV (12 random bytes) is prepended to the ciphertext so decrypt can split them back apart.

function uint8ArrayToBase64(uint8: Uint8Array): string {
  if (uint8.toBase64) {
    return uint8.toBase64();
  }
  return btoa(String.fromCharCode(...uint8));
}

function base64ToUint8Array(base64: string): Uint8Array<ArrayBuffer> {
  if (Uint8Array.fromBase64) {
    return Uint8Array.fromBase64(base64);
  }
  const binaryString = atob(base64);
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}

async function encrypt(plaintext: string, rawKey: BufferSource): Promise<Uint8Array> {
  const encoder = new TextEncoder();
  const data = encoder.encode(plaintext);
  const key = await crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["encrypt"]);
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, data);
  const combined = new Uint8Array(iv.length + ciphertext.byteLength);
  combined.set(iv);
  combined.set(new Uint8Array(ciphertext), iv.length);
  return combined;
}

async function decrypt(combinedData: Uint8Array, rawKey: BufferSource): Promise<string> {
  const iv = combinedData.slice(0, 12);
  const ciphertext = combinedData.slice(12);
  const key = await crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["decrypt"]);
  const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
  return new TextDecoder().decode(decrypted);
}

Enter fullscreen mode Exit fullscreen mode

jwksStore (JwksKeyStore)

storeKeyPair is called by JoseJwksAuthority whenever a new key pair is generated. The four-step envelope encryption process runs here:

export const jwksStore: JwksKeyStore = {
  async storeKeyPair(kid: string, privateKey: object, publicKey: object, ttl: number) {
    // 1. Generate a fresh, unique DEK (Data Encryption Key)
    const dekRaw = crypto.getRandomValues(new Uint8Array(32));

    // 2. Encrypt the private key with the DEK
    const encryptedPrivateKey = await encrypt(JSON.stringify(privateKey), dekRaw);

    // 3. Wrap (encrypt) the DEK using the Master Key (KEK)
    const wrappedDek = await encrypt(uint8ArrayToBase64(dekRaw), MASTER_KEY_RAW);

    // 4. Store the encrypted private key and the wrapped DEK together
    const expirationTime = Date.now() + ttl * 1000;
    const privateKeyRecord: PrivateKeyRecord = {
      keyId: kid,
      privateKey: uint8ArrayToBase64(encryptedPrivateKey),
      wrappedDek: uint8ArrayToBase64(wrappedDek),
    };
    const publicKeyRecord: PublicKeyRecord = {
      keyId: kid,
      publicKey: JSON.stringify(publicKey),
    };

    await saveKeyPairRecord(privateKeyRecord, publicKeyRecord, expirationTime);
  },

  async getPublicKeys(): Promise<object[]> {
    const publicKeyRecords = await getPublicKeyRecords();
    if (!publicKeyRecords) {
      return [];
    }
    return publicKeyRecords.map((record) => JSON.parse(record.publicKey));
  },

  async getPrivateKey(): Promise<object | undefined> {
    const privateKeyRecord = await getPrivateKeyRecord();
    if (!privateKeyRecord) {
      return undefined;
    }

    // 1. Unwrap (decrypt) the DEK using the Master Key (KEK)
    const wrappedDekBytes = base64ToUint8Array(privateKeyRecord.wrappedDek);
    const dekRawString = await decrypt(wrappedDekBytes, MASTER_KEY_RAW);
    const dekRaw = base64ToUint8Array(dekRawString);

    // 2. Decrypt the private key using the DEK
    const decryptedPrivateKeyString = await decrypt(
      base64ToUint8Array(privateKeyRecord.privateKey),
      dekRaw
    );

    return JSON.parse(decryptedPrivateKeyString);
  },
};

Enter fullscreen mode Exit fullscreen mode

getPrivateKey reverses the process exactly: decode from Base64, unwrap the DEK with the KEK, then decrypt the private key with the DEK.

rotationTimestampStore (JwksRotationTimestampStore)

JwksRotator uses this interface to decide whether it's time to rotate. The persistent implementation reads created_at from the private key row directly, so no additional table is needed here.

setLastRotationTimestamp is intentionally left empty. The rotation timestamp is implicitly captured when storeKeyPair inserts a new row, created_at defaults to now(). Keeping a separate timestamp in sync would be redundant and risk drift.

export const rotationTimestampStore: JwksRotationTimestampStore = {
  async getLastRotationTimestamp(): Promise<number> {
    const createdAt = await getPrivateKeyCreatedAt();
    if (!createdAt) {
      return 0; // No keys yet, treat as never rotated
    }
    return createdAt.getTime();
  },

  async setLastRotationTimestamp(_timestamp: number): Promise<void> {
    // No-op: the rotation timestamp is derived from private_keys.created_at
  },
};

Enter fullscreen mode Exit fullscreen mode


Step 4: Update src/index.ts

The change is minimal: swap the import and remove the local createInMemoryKeyStore() call.

Before:

import {
  createInMemoryKeyStore,
  JoseJwksAuthority,
  JwksRotator,
} from "@saurbit/oauth2-jwt";

// ...

const jwksStore = createInMemoryKeyStore();
const jwksAuthority = new JoseJwksAuthority(jwksStore, 8.64e6);

const jwksRotator = new JwksRotator({
  keyGenerator: jwksAuthority,
  rotationTimestampStore: jwksStore, // same object fulfilled both interfaces
  rotationIntervalMs: 7.884e9,
});

Enter fullscreen mode Exit fullscreen mode

After:

import { jwksStore, rotationTimestampStore } from "./stores";
import { JoseJwksAuthority, JwksRotator } from "@saurbit/oauth2-jwt";

// ...

const jwksAuthority = new JoseJwksAuthority(jwksStore, 8.64e6);

const jwksRotator = new JwksRotator({
  keyGenerator: jwksAuthority,
  rotationTimestampStore: rotationTimestampStore, // now a separate object
  rotationIntervalMs: 7.884e9,
});

Enter fullscreen mode Exit fullscreen mode

The rest of index.ts does not change.


Step 5: Run the server

Set the required environment variables and start the server:

bunx cross-env DATABASE_URL="postgres://..." MASTER_KEY="<base64-32-bytes>" bun dev

Enter fullscreen mode Exit fullscreen mode

On startup, jwksRotator.checkAndRotateKeys() runs. If the private_keys table is empty (or the current key has passed the rotation interval), a new RSA key pair is generated, encrypted, and stored. The public key is written to public_keys and will be returned from /.well-known/jwks.json immediately.


Key rotation behavior

The server checks the rotation schedule on startup and then once per hour via setInterval. Here is what happens at each check:

  1. getLastRotationTimestamp() reads created_at from the active private key row. If no row exists, it returns 0.
  2. If now - lastRotation >= rotationIntervalMs (91 days in the example), JoseJwksAuthority.generateKeyPair() is called.
  3. storeKeyPair runs: the new private key overwrites the single private_keys row; a new row is appended to public_keys.
  4. The old public key row stays in public_keys until its expires_at is reached. During this window, both the old and new public keys are served from the JWKS endpoint, so tokens signed with the old key continue to verify correctly.

The key lifetime passed to JoseJwksAuthority (8.64e6 ms = 100 days) controls the expires_at stored in the database. It should be longer than the rotation interval (91 days) to ensure the overlap window exists.


Conclusion

This article showed how to implement a persistent key store for the OIDC server using PostgreSQL and envelope encryption. With this setup, signing keys survive server restarts and work correctly across multiple instances.

The management of cryptographic keys is a critical aspect of any authentication system, and this implementation provides a secure and scalable solution for handling keys in a real-world environment.


What's next

  • Add a consent screen for multi-tenant or third-party client scenarios
  • Support the refresh_token grant to issue long-lived sessions