Keys Worker (keys.js) – Function Documentation

This Cloudflare Worker script provides a secure API for retrieving secret keys from environment variables, with CORS support and authentication.

Key Components

1. @typedef {Object} Env

Documents the expected environment variables:

  • R2_KEY_SECRET: Secret for R2 storage access.

  • SL_API_KEY: API key for a third-party service.

  • CFT_PUBLIC_KEY: Public key for Cloudflare Turnstile.

  • CFT_SECRET_KEY: Secret key for Cloudflare Turnstile.


2. corsHeaders

CORS and content-type headers to allow requests from the Striae app domain and support plain text responses.


3. hasValidHeader(request, env)

Checks if the incoming request contains a valid X-Custom-Auth-Key header matching the secret in the environment (env.KEYS_AUTH).
Returns: true if valid, false otherwise.


4. fetch(request, env)

The main entry point for the worker. Handles HTTP requests for key retrieval.

Request Handling:

  • OPTIONS:
    Returns CORS headers for preflight requests.

  • Authentication:
    Rejects requests without a valid X-Custom-Auth-Key header.

  • Key Name Extraction:
    Extracts the key name from the URL path.

  • Validation:

    • Returns a 400 error if no key name is provided.

    • Returns a 404 error if the key is not found in the environment.

  • Key Retrieval:
    Returns the value of the requested key as plain text.


Usage

This worker is intended to be deployed on Cloudflare and used as a backend for secure, authenticated retrieval of secret keys (such as API tokens), with CORS enabled for the main application domain.

Updated on