Floryne Pierson
← All posts

Building an API key system without a library

SHA-256 the key on arrival, store only the hash, check the quota, increment usage as a fire-and-forget. No package, no magic. The raw key never touches the database.

When I opened the Magical Chart astronomy API to external agents and developers, I needed a key management system: issue keys, validate them on each request, enforce monthly quotas, and revoke them if needed. The constraint was that if the database were ever compromised, a leaked key hash should be useless to an attacker who does not have the original key.

The implementation is a single file, 85 lines, no external dependencies beyond Node's built-in crypto module.

1. The raw key never touches the database

The only thing stored in the database is a SHA-256 hash of the key. The raw key is generated once at issuance, shown to the user once, and never stored anywhere:

import { createHash } from 'crypto'

function hashKey(raw) {
  return createHash('sha256').update(raw).digest('hex')
}

SHA-256 is a one-way function: given the hash, there is no efficient path back to the original key. If a database backup leaks, the attacker has a list of hex strings that are useless without the originals. This is the same approach used by GitHub and npm for their API tokens.

All keys have a fixed prefix. This makes them easy to identify in logs and allows immediate recognition and revocation if one appears somewhere it should not.

2. Validation on each request

The incoming request must carry a Bearer token in the Authorization header. The extraction function rejects anything that does not match the expected format:

export function extractBearerKey(req) {
  const auth = req.headers['authorization'] || ''
  if (!auth.startsWith('Bearer ')) return null
  const key = auth.slice('Bearer '.length).trim()
  return key.length > 0 ? key : null
}

Once extracted, the key is hashed and looked up in the database by hash. The database query never uses the raw key string:

const hash = hashKey(rawKey)
// look up by hash — raw key never sent to the database
const rec = await db.findKeyByHash(hash)
if (!rec) return { ok: false, reason: 'invalid_key' }
if (!rec.active) return { ok: false, reason: 'inactive_key' }

3. Monthly quota reset

Each key record stores a reset timestamp and a usage counter. If the current time has passed the reset timestamp, the counter resets to zero before the quota check runs:

const now = new Date()
let callsUsed = rec.callsUsed

if (now >= rec.resetAt) {
  callsUsed = 0
  const nextReset = new Date(
    Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)
  )
  await db.resetKeyUsage(rec.id, nextReset)
}

The reset timestamp is always set to the first day of the next calendar month in UTC. This means the reset happens at a predictable time regardless of when the key was issued or when this particular request lands.

Keys can be configured as unlimited. The quota check skips entirely for those:

if (!rec.unlimited && callsUsed >= rec.callsLimit) {
  return { ok: false, reason: 'quota_exceeded' }
}

4. Fire-and-forget usage increment

Once the key is validated and the request is allowed through, the usage counter increments. This write does not block the response:

db.incrementUsage(rec.id, now).catch(() => {})

The .catch(() => {}) is intentional. If the usage increment fails (database briefly unavailable, network blip), the request still succeeds. The counter might be off by one, but the caller gets their response without added latency. The alternative is making every API call wait for a write to complete, which adds a database round-trip to every request's critical path for the sake of a counter that is only used for monthly reporting.

The tradeoff: fire-and-forget means the counter can undercount if writes fail. For a quota system where being off by a few calls per month is acceptable, this is the right call. For billing where every call must be counted, you would want a synchronous write or a queue.

5. Standardized error responses

Every validation failure returns the same structure, with a reason field that makes the failure machine-readable and a human message pointing to the documentation:

export function unauthorizedResponse(res, reason) {
  const messages = {
    invalid_key:    'Invalid API key.',
    inactive_key:   'This API key has been deactivated.',
    quota_exceeded: 'Monthly quota exceeded.',
    server_config:  'Server configuration error.',
  }
  res.setHeader('WWW-Authenticate', 'Bearer')
  return res.status(401).json({
    error: 'unauthorized',
    reason,
    message: messages[reason] || 'Unauthorized.',
  })
}

The WWW-Authenticate header is part of the HTTP spec for 401 responses. Including it means that any HTTP client that handles authentication automatically will prompt correctly, and that API testing tools like Bruno or Insomnia recognize the authentication scheme without manual configuration.