DEV Community

Preventing Cross-Account Cache Leaks and Hardening TTL Parsing in JavaScript (With Vitest)

Caching API responses in browser extensions and frontend apps looks simple - until a user switches accounts, toggles an auth token, or enters an invalid cache duration in settings.

While working on FOSSASIA's Scrum Helper, we ran into two subtle bugs that show up in almost every client-side caching layer:

  • Cross-account / stale-auth cache leaks when cache keys ignore token state or leak raw secrets into local storage.
  • Silent TTL corruption when browser.storage.local returns unexpected strings, zero/negative numbers, or overflowing integers.

Here is how we fixed both in JavaScript and locked the behavior down with parameterized Vitest suites.

The Cache Leak Trap (and Why Raw Tokens Don't Belong in Keys)

Suppose your app fetches activity from GitLab or Codeberg and builds a cache key like this:

// ❌ Buggy: changing tokens or filters still hits the old cache!
const cacheKey = `${baseUrl}-${username}-${startDate}-${endDate}`;

If a user first loads public data (token = null) and then adds a personal access token to fetch private repositories, the username and dates haven't changed - so the cache serves stale unauthenticated results. Even worse, if two tokens belong to different scopes, switching tokens can expose cached data from the previous session.

The obvious fix - appending ${token} directly to cacheKey - creates a security bug: if you persist cacheKey in browser.storage.local or log it for debugging, you've just stored a plaintext secret in cache metadata.

Fix: Deterministic Token Fingerprinting (getTokenMarker)

Instead of storing the raw token, hash it into a compact, non-reversible marker (auth- or noauth):

function getTokenMarker(token) {
  if (!token) return 'noauth';
  let hash = 0;
  for (let i = 0; i < token.length; i++) {
    hash = (hash << 5) - hash + token.charCodeAt(i);
    hash |= 0;
  }
  return `auth-${Math.abs(hash).toString(16)}`;
}

Then combine it with normalized filter markers (sorted and lowercased so order differences don't cause unnecessary cache misses):

const tokenMarker = getTokenMarker(token);
const normalizedGroups = parseGitlabGroups(orgName).sort().join(',');
const orgMarker = normalizedGroups ? `org-${normalizedGroups}` : 'noorg';
let repoMarker = 'norepos';
if (isRepoFilterEnabled && selectedReposList && selectedReposList.length > 0) {
  const repoNames = selectedReposList
    .filter(Boolean)
    .map((r) => (typeof r === 'object' && r !== null ? r.fullName || '' : r || '').toLowerCase())
    .filter(Boolean)
    .sort()
    .join(',');
  repoMarker = `repos-${repoNames}`;
}

Now:

  • Plaintext tokens never enter storage or logs.
  • Switching between unauthenticated (noauth), token-a, and token-b immediately isolates cache entries.
  • Toggling repository or group filters cleanly invalidates stale data.

Hardening Cache TTL Against Corrupt Storage Values

User-configured cache durations often come from form inputs saved to browser.storage.local. Using parseInt(val) * 60 * 1000 without strict bounds checking breaks in subtle ways:

  • 0 or -5 turns caching off or keeps entries perpetually expired.
  • abc produces NaN.
  • Huge numbers like '9'.repeat(304) overflow to Infinity, and integers beyond Number.MAX_SAFE_INTEGER lose precision.
  • Storage calls can reject outright in restricted browser contexts.

Fix: Number.isSafeInteger + Safe Fallback

async getCacheTTL() {
  const defaultTtl = 10 * 60 * 1000; // 10 minutes
  try {
    const items = await browser.storage.local.get(['cacheInput']);
    const minutes = Number.parseInt(items.cacheInput, 10);
    return Number.isSafeInteger(minutes) && minutes > 0 ? minutes * 60 * 1000 : defaultTtl;
  } catch (error) {
    console.error('Error getting cache TTL:', error);
    return defaultTtl;
  }
}

Checking Number.isSafeInteger(minutes) && minutes > 0 guarantees that getCacheTTL() always resolves to a finite, positive number of milliseconds - even if storage throws or contains garbage.

Verifying Both Helpers Together with Vitest (describe.each)

When two providers (GitLabHelper and CodebergHelper) must uphold the exact same cache-isolation and TTL contracts, duplicating test files drifts quickly. Using Vitest's describe.each, we ran one unified contract suite against both classes:

import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import GitLabHelper from '../src/scripts/gitlabHelper.js';
import CodebergHelper from '../src/scripts/codebergHelper.js';

const DEFAULT_TTL_MS = 10 * 60 * 1000;

function mockCacheInput(value) {
  vi.spyOn(browser.storage.local, 'get').mockResolvedValue(
    value === undefined ? {} : { cacheInput: value },
  );
}

const helpers = [
  ['GitLabHelper', () => new GitLabHelper('https://gitlab.com')],
  ['CodebergHelper', () => new CodebergHelper('https://codeberg.org/api/v1')],
];

describe.each(helpers)('%s getCacheTTL', (_name, create) => {
  let helper;
  beforeEach(() => {
    helper = create();
  });
  afterEach(() => {
    vi.restoreAllMocks();
  });
  it('should always resolve to a finite, positive TTL', async () => {
    for (const value of ['abc', '0', '-5', '', '9'.repeat(304), '9007199254740993', undefined, null, {}]) {
      mockCacheInput(value);
      const ttl = await helper.getCacheTTL();
      expect(Number.isFinite(ttl)).toBe(true);
      expect(ttl).toBeGreaterThan(0);
      expect(ttl).toBe(DEFAULT_TTL_MS);
    }
  });
});

describe.each(helpers)('%s getTokenMarker', (_name, create) => {
  let helper;
  beforeEach(() => {
    helper = create();
  });
  it('should return hashed marker without exposing the raw token', () => {
    const marker = helper.getTokenMarker('super-secret-token');
    expect(marker).toMatch(/^auth-[a-f0-9]+$/);
    expect(marker).not.toContain('super-secret-token');
  });
  it('should return distinct markers for distinct tokens', () => {
    expect(helper.getTokenMarker('token-a')).not.toBe(helper.getTokenMarker('token-b'));
  });
});

Key Takeaways

  • Never put raw auth tokens into cache keys - fingerprint them into deterministic markers.
  • Normalize multi-value filter inputs (toLowerCase().sort().join(',')) before building cache keys.
  • Guard numeric settings with Number.isSafeInteger(n) && n > 0 instead of trusting parseInt alone.
  • Use describe.each in Vitest to enforce identical security and edge-case guarantees across multiple API helpers.

You can check out more of my open-source work across FOSSASIA and Apache on GitHub.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.