npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@moikapy/openrouter-auth

v0.1.0

Published

OAuth PKCE + AES-256-GCM encryption for OpenRouter — framework-agnostic, Cloudflare Workers compatible, with React components

Downloads

17

Readme

@moikapy/openrouter-auth

OAuth PKCE + AES-256-GCM encryption for OpenRouter — framework-agnostic, Cloudflare Workers compatible, with React components.

Handles the full OpenRouter OAuth flow: user clicks "Connect" → PKCE redirect → callback exchange → encrypted API key stored in httpOnly cookie.

Security

  • AES-256-GCM authenticated encryption — can't tamper without detection
  • Key rotation — encrypt with current key, decrypt with current or previous keys. Transparent re-encryption on read.
  • Session expiry — timestamp embedded inside ciphertext (can't be forged). Default 30-day expiry enforced server-side.
  • PKCE S256 — verifier never sent over the wire
  • httpOnly + Secure + SameSite=Lax — JS can't read cookie, CSRF-protected
  • HTTPS validation — rejects non-HTTPS auth URLs (localhost exempt)

Install

bun add @moikapy/openrouter-auth

Prerequisites

  1. OpenRouter OAuth app — register at openrouter.ai to get a client_id
  2. Encryption key — generate: openssl rand -hex 32
  3. Environment — set OPENROUTER_ENCRYPT_KEY (or pass explicitly)
  4. For key rotation — set OPENROUTER_ENCRYPT_KEY_PREVIOUS (comma-separated old keys)

React Components (quickest path)

import { OpenRouterConnect, OpenRouterCallback } from "@moikapy/openrouter-auth/react";

// Any page — renders connect/disconnect UI
<OpenRouterConnect
  onConnected={() => console.log("connected!")}
  onDisconnected={() => console.log("disconnected")}
/>

// /auth/callback page — handles post-redirect code exchange
<OpenRouterCallback redirectUrl="/" />

// Full control via render prop
<OpenRouterConnect>
  {({ connected, connect, disconnect, loading, error }) =>
    connected
      ? <button onClick={disconnect}>Disconnect</button>
      : <button onClick={connect} disabled={loading}>Connect</button>
  }
</OpenRouterConnect>

Server-side (Next.js)

import { getApiKeyFromCookie, exchangeCodeAndSetCookie } from "@moikapy/openrouter-auth/next";

// Callback route — exchange code, encrypt, set cookie
const encrypted = await exchangeCodeAndSetCookie(code, verifier, {
  encryptKey: process.env.OPENROUTER_ENCRYPT_KEY,
  previousKeys: process.env.OPENROUTER_ENCRYPT_KEY_PREVIOUS?.split(","),
});

// Any route — get decrypted API key (auto re-encrypts if key was rotated)
const apiKey = await getApiKeyFromCookie({
  encryptKey: process.env.OPENROUTER_ENCRYPT_KEY,
  previousKeys: process.env.OPENROUTER_ENCRYPT_KEY_PREVIOUS?.split(","),
});

Server-side (Express, Hono, etc.)

import { exchangeAndEncrypt, decryptFromCookie, buildCookieOptions } from "@moikapy/openrouter-auth/server";

// Callback
const encrypted = await exchangeAndEncrypt(code, verifier, {
  encryptKey: process.env.OPENROUTER_ENCRYPT_KEY,
});
res.cookie("or_session", encrypted, buildCookieOptions());

// Any route
const result = await decryptFromCookie(req.cookies.or_session, {
  encryptKey: process.env.OPENROUTER_ENCRYPT_KEY,
});
if (!result) return res.status(401).json({ error: "Not connected or session expired" });

// If key was rotated, re-encrypt and update the cookie
if (result.needsReEncrypt) {
  const newCookie = await encryptForCookie(result.apiKey, { encryptKey: process.env.OPENROUTER_ENCRYPT_KEY });
  res.cookie("or_session", newCookie, buildCookieOptions());
}

Key Rotation

When you need to rotate the encryption key:

  1. Generate a new key: openssl rand -hex 32
  2. Set OPENROUTER_ENCRYPT_KEY to the new key
  3. Set OPENROUTER_ENCRYPT_KEY_PREVIOUS to the old key
  4. Existing cookies decrypt with the old key and auto re-encrypt with the new key on read
  5. After 30 days (or your sessionMaxAge), remove OPENROUTER_ENCRYPT_KEY_PREVIOUS
  6. Users with old cookies will get null from getApiKeyFromCookie and need to re-authenticate

Session Expiry

Sessions expire in 30 days by default. This is enforced two ways:

  1. Cookie maxAge — browser deletes the cookie after 30 days
  2. Embedded timestamp — encrypted inside the ciphertext, can't be tampered with. Server rejects expired sessions even if the cookie is still present.

Configure with sessionMaxAge (seconds):

// 7-day sessions
await getApiKeyFromCookie({
  encryptKey: process.env.OPENROUTER_ENCRYPT_KEY,
  sessionMaxAge: 7 * 24 * 60 * 60,
});

Exports

| Path | Runtime | Description | |---|---|---| | @moikapy/openrouter-auth | Any | Types + re-exports | | @moikapy/openrouter-auth/react | React | <OpenRouterConnect> + <OpenRouterCallback> | | @moikapy/openrouter-auth/pkce | Browser | PKCE flow: start, check, disconnect | | @moikapy/openrouter-auth/server | Any server | Framework-agnostic helpers | | @moikapy/openrouter-auth/next | Next.js | next/headers cookie helpers | | @moikapy/openrouter-auth/crypto | Anywhere | Low-level encrypt/decrypt with rotation |

Encrypted Format

[0x01] [keyFingerprint:4] [timestamp:4] [iv:12] [ciphertext+authTag]
  • 0x01 — format version
  • keyFingerprint — first 4 bytes of SHA-256(encryption key), identifies which key to use for decryption
  • timestamp — uint32 seconds since epoch (valid until 2106), enforced on decrypt
  • iv — 12-byte random IV (unique per encryption)
  • ciphertext+authTag — AES-256-GCM output with 16-byte authentication tag

License

MIT