auth/keyring.ts

Key ring for cookie signing.

Encapsulates secret keys and crypto operations. Keys are never exposed - only sign/verify operations are available. This prevents accidental logging or leakage of secrets.

@example

const keyring = create_keyring(process.env.SECRET_COOKIE_KEYS); if (!keyring) throw new Error('No keys configured'); const signed = await keyring.sign('user:123:1700000000'); const result = await keyring.verify(signed); // result = { value: 'user:123:1700000000', key_index: 0 }

Declarations
#

5 declarations

view source

create_keyring
#

auth/keyring.ts view source

(env_value: string | undefined): Keyring | null

Create a keyring from environment variable.

Keys are separated by __ for rotation support. First key is used for signing, all keys are tried for verification.

CryptoKeys are cached on first use for performance.

Security: key rotation is an operational concern. Old keys remain valid for verification indefinitely — a leaked old key can forge session cookies until it is removed from SECRET_COOKIE_KEYS. After rotating to a new signing key, remove the old key within a grace period (e.g. 24–48 hours, long enough for active sessions to re-sign with the new key via cookie refresh). Treat SECRET_COOKIE_KEYS changes as security-critical deploys.

env_value

the SECRET_COOKIE_KEYS environment variable

type string | undefined

returns

Keyring | null

keyring or null if no keys configured

create_validated_keyring
#

auth/keyring.ts view source

(env_value: string | undefined): ValidatedKeyringResult

Validate and create a keyring in one step.

Returns a discriminated union so callers handle exit/logging their own way (e.g. Deno.exit(1) vs runtime.exit(1)).

env_value

the SECRET_COOKIE_KEYS environment variable

type string | undefined

returns

ValidatedKeyringResult

{ok: true, keyring} or {ok: false, errors}

Keyring
#

auth/keyring.ts view source

Keyring

Opaque keyring that encapsulates secret keys. Only exposes sign/verify operations, never the raw keys.

sign

Sign a value with HMAC SHA-256.

type (value: string) => Promise<string>

verify

Verify a signed value and extract the original. Tries all keys in order to support key rotation.

type (signed_value: string) => Promise<{value: string; key_index: number} | null>

validate_keyring
#

auth/keyring.ts view source

(env_value: string | undefined): string[]

Validate key ring configuration.

env_value

the SECRET_COOKIE_KEYS environment variable

type string | undefined

returns

string[]

array of validation errors (empty if valid)

ValidatedKeyringResult
#

Imported by
#