cap icon indicating copy to clipboard operation
cap copied to clipboard

Feature Request: Web‑standard version of @cap.js for Serverless Runtimes

Open mertushka opened this issue 1 year ago • 4 comments

Problem

@cap.js/server currently depends heavily on Node.js built‑in APIs (fs, crypto, events, process, etc.). This requires enabling the compatibility mode in Cloudflare Workers ("compatibility_flags": ["nodejs_compat"] ), which adds unnecessary overhead and reduces portability. Also, It limits future portability to other Web‑Standard environments such as Service Workers, Deno, or edge runtimes without Node compatibility

Feature Request

Create a @cap.js/cloudflare-worker (or similarly named) package that:

  • Uses Web‑Standard APIs (Web Crypto, EventTarget etc.) instead of Node‑specific APIs
  • Avoids fs, events, process, and other Node globals
  • Runs natively in Cloudflare Workers without "nodejs_compat"
  • Keeps the same API as @cap.js/server where possible for easy migration

mertushka avatar Aug 01 '25 16:08 mertushka

pretty interesting, i'll look into it.

tiagozip avatar Aug 01 '25 17:08 tiagozip

@tiagozip Thanks! I’d love to contribute if you create a draft PR that we can work on.

mertushka avatar Aug 01 '25 17:08 mertushka

@tiagozip Here is the version i am using right now, removed all "state" and Node related things and just using storage hooks.

/**
 * Generates a deterministic hex string of given length from a string seed
 *
 * @param {string} seed - Initial seed value
 * @param {number} length - Output hex string length
 * @returns {string} Deterministic hex string generated from the seed
 */
function prng(seed, length) {
  /**
   * @param {string} str
   */
  function fnv1a(str) {
    let hash = 2166136261;
    for (let i = 0; i < str.length; i++) {
      hash ^= str.charCodeAt(i);
      hash +=
        (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
    }
    return hash >>> 0;
  }

  let state = fnv1a(seed);
  let result = "";

  function next() {
    state ^= state << 13;
    state ^= state >>> 17;
    state ^= state << 5;
    return state >>> 0;
  }

  while (result.length < length) {
    const rnd = next();
    result += rnd.toString(16).padStart(8, "0");
  }

  return result.substring(0, length);
}

/**
 * Generates a random hex string of given byte length
 *
 * @param {number} bytesLength - Length in bytes
 * @returns {string} Random hex string
 */

function randomHex(bytesLength) {
  const array = new Uint8Array(bytesLength);
  crypto.getRandomValues(array);
  return Array.from(array, (b) => b.toString(16).padStart(2, "0")).join("");
}

/**
 * Computes SHA-256 hash of a string and returns it as a hex string
 *
 * @param {string} input - Input string to hash
 * @returns {Promise<string>} SHA-256 hash as a hex string
 */

async function sha256Hex(input) {
  const encoder = new TextEncoder();
  const data = encoder.encode(input);
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
}

/**
 * Main Cap class
 */
class Cap {
  /** @type {Promise<void>|null} */

  /** @type {CapConfig} */
  config;

  /**
   * Creates a new Cap instance
   * @param {Partial<CapConfig>} [configObj] - Configuration object
   */
  constructor(configObj) {
    /** @type {CapConfig} */
    this.config = {
      storage: {
        challenges: {},
        tokens: {},
      },
      ...configObj,
    };
  }

  /**
   * Retrieves challenge data from storage
   * @private
   * @param {string} token - Challenge token
   * @returns {Promise<ChallengeData|null>} Challenge data or null if not found
   */
  async _getChallenge(token) {
    if (this.config.storage?.challenges?.read) {
      return (await this.config.storage.challenges.read(token)) || null;
    }
  }

  /**
   * Deletes challenge from storage
   * @private
   * @param {string} token - Challenge token
   * @returns {Promise<void>}
   */
  async _deleteChallenge(token) {
    if (this.config.storage?.challenges?.delete) {
      await this.config.storage.challenges.delete(token);
    }
  }

  /**
   * Generates a new challenge
   * @param {ChallengeConfig} [conf] - Challenge configuration
   * @returns {Promise<{ challenge: {c: number, s: number, d: number}, token?: string, expires: number }>} Challenge data
   */
  async createChallenge(conf) {
    /** @type {{c: number, s: number, d: number}} */
    const challenge = {
      c: conf?.challengeCount ?? 50,
      s: conf?.challengeSize ?? 32,
      d: conf?.challengeDifficulty ?? 4,
    };

    const token = randomHex(25);
    const expires = Date.now() + (conf?.expiresMs ?? 600000);

    if (conf && conf.store === false) {
      return { challenge, expires };
    }

    const challengeData = { expires, challenge };

    if (this.config.storage?.challenges?.store) {
      await this.config.storage.challenges.store(token, challengeData);
    }

    return { challenge, token, expires };
  }

  /**
   * Redeems a challenge solution in exchange for a token
   * @param {Solution} param0 - Challenge solution data
   * @returns {Promise<{success: boolean, message?: string, token?: string, expires?: number}>}
   */
  async redeemChallenge({ token, solutions }) {
    if (
      !token ||
      !solutions ||
      !Array.isArray(solutions) ||
      solutions.some((s) => typeof s !== "number")
    ) {
      return { success: false, message: "Invalid body" };
    }

    const challengeData = await this._getChallenge(token);
    await this._deleteChallenge(token);

    if (!challengeData || challengeData.expires < Date.now()) {
      return { success: false, message: "Challenge invalid or expired" };
    }

    let i = 0;

    const challenges = Array.from({ length: challengeData.challenge.c }, () => {
      i = i + 1;

      return [
        prng(`${token}${i}`, challengeData.challenge.s),
        prng(`${token}${i}d`, challengeData.challenge.d),
      ];
    });

    const isValid = await Promise.all(
      challenges.map(async ([salt, target], i) => {
        return (
          solutions[i] &&
          (await sha256Hex(salt + solutions[i])).startsWith(target)
        );
      })
    );

    if (!isValid) return { success: false, message: "Invalid solution" };

    const vertoken = randomHex(15);
    const expires = Date.now() + 20 * 60 * 1000;
    const hash = await sha256Hex(vertoken);
    const id = randomHex(8);
    const tokenKey = `${id}:${hash}`;

    if (this.config.storage?.tokens?.store) {
      await this.config.storage.tokens.store(tokenKey, expires);
    }

    return { success: true, token: `${id}:${vertoken}`, expires };
  }

  /**
   * Retrieves token expiration from storage
   * @private
   * @param {string} tokenKey - Token key
   * @returns {Promise<number|null>} Token expiration or null if not found
   */
  async _getToken(tokenKey) {
    if (this.config.storage?.tokens?.get) {
      return await this.config.storage.tokens.get(tokenKey);
    }
  }

  /**
   * Deletes token from storage
   * @private
   * @param {string} tokenKey - Token key
   * @returns {Promise<void>}
   */
  async _deleteToken(tokenKey) {
    if (this.config.storage?.tokens?.delete) {
      await this.config.storage.tokens.delete(tokenKey);
    }
  }

  /**
   * Validates a token
   * @param {string} token - The token to validate
   * @param {TokenConfig} [conf] - Validation configuration
   * @returns {Promise<{success: boolean}>}
   */
  async validateToken(token, conf) {
    if (!token || typeof token !== "string") {
      return { success: false };
    }

    const parts = token.split(":");
    if (parts.length !== 2 || !parts[0] || !parts[1]) {
      return { success: false };
    }

    const [id, vertoken] = parts;
    const hash = await sha256Hex(vertoken);
    const key = `${id}:${hash}`;

    const tokenExpires = await this._getToken(key);

    if (!tokenExpires) {
      return { success: false };
    }

    if (tokenExpires && tokenExpires > Date.now()) {
      if (!conf?.keepToken) {
        await this._deleteToken(key);
      }
      return { success: true };
    }

    return { success: false };
  }

  /**
   * Removes expired tokens and challenges from memory and storage
   * @private
   * @returns {Promise<boolean>} - True if any tokens were changed/removed
   */
  async _cleanExpiredTokens() {
    if (this.config.storage?.challenges?.listExpired) {
      const expiredChallenges =
        await this.config.storage.challenges.listExpired();

      await Promise.all(
        expiredChallenges.map(async (token) => {
          await this._deleteChallenge(token);
        })
      );
    } else {
      console.warn(
        "[cap] challenge storage hooks provided but no listExpired, couldn't delete expired challenges"
      );
    }

    if (this.config.storage?.tokens?.listExpired) {
      const expiredTokens = await this.config.storage.tokens.listExpired();
      await Promise.all(
        expiredTokens.map(async (tokenKey) => {
          await this._deleteToken(tokenKey);
        })
      );
    } else {
      console.warn(
        "[cap] token storage hooks provided but no listExpired, couldn't delete expired tokens"
      );
    }
  }

  /**
   * Cleans up expired tokens and syncs state
   * @returns {Promise<void>}
   */
  async cleanup() {
    await this._cleanExpiredTokens();
  }
}

/** @type {typeof Cap} */
export default Cap;

mertushka avatar Aug 01 '25 19:08 mertushka

Changed the title to cover not only ‘@cap.js/server’ but also ‘@cap.js/checkpoint-*’ checkpoint middlewares and any future packages. Updated “Cloudflare Workers” to the broader term “Serverless Runtimes” (Vercel Edge Functions, AWS Lambda etc.) for clarity.

mertushka avatar Aug 03 '25 18:08 mertushka

@tiagozip I just published https://github.com/mertushka/cap-worker. You might wanna check it out!

mertushka avatar Aug 08 '25 18:08 mertushka

that looks great, thank you! ill close this issue while I look into adding this to the main libraries

tiagozip avatar Aug 11 '25 09:08 tiagozip