@paralleldrive/cuid2 Documentation

repository·main·Indexed 25 days ago

https://github.com/paralleldrive/cuid2

A library for generating secure, collision-resistant, and horizontally scalable IDs optimized for performance and distributed systems. It provides a next-generation alternative to UUIDs and GUIDs, featuring a programmatic API with createId(), init() for custom configurations (length, fingerprint, random functions), and isCuid() for validation. Also includes a CLI for generating IDs and short slugs.

Tokens
9K
Snippets
28
Records
53
Agent score
82%

What's inside @paralleldrive/cuid2

  1. Configure Jest with a custom JSDOM environment

    main

    Jest's jsdom environment has known issues where new TextEncoder().encode() and new Uint8Array() produce different results. To fix this, you must create a custom environment that overwrites the Uint8Array provided by jsdom.

    1. Install jest-environment-jsdom (ensure the version matches your Jest version, e.g., @27):
      npm i jest-environment-jsdom@27
    2. Create a jsdom-env.js file in your project root:
      const JSDOMEnvironmentBase = require("jest-environment-jsdom");
      
      Object.defineProperty(exports, "__esModule", {
        value: true,
      });
      
      class JSDOMEnvironment extends JSDOMEnvironmentBase {
        constructor(...args) {
          const { global } = super(...args);
          global.Uint8Array = Uint8Array;
        }
      }
      
      exports.default = JSDOMEnvironment;
      exports.TestEnvironment = JSDOMEnvironment;
    3. Update your package.json test script to use this environment:
      "scripts": {
        "test": "react-scripts test --env=./jsdom-env.js"
      }
    const JSDOMEnvironmentBase = require("jest-environment-jsdom");
    
    Object.defineProperty(exports, "__esModule", {
      value: true,
    });
    
    class JSDOMEnvironment extends JSDOMEnvironmentBase {
      constructor(...args) {
        const { global } = super(...args);
    
        global.Uint8Array = Uint8Array;
      }
    }
    
    exports.default = JSDOMEnvironment;
    exports.TestEnvironment = JSDOMEnvironment;
  2. Install @paralleldrive/cuid2

    main

    To use Cuid2 in your project, install the package via npm or yarn.

    npm install --save @paralleldrive/cuid2

    Or

    yarn add @paralleldrive/cuid2
    npm install --save @paralleldrive/cuid2
    
    yarn add @paralleldrive/cuid2
  3. Use the Cuid2 CLI

    main

    You can generate IDs from the command line using npx @paralleldrive/cuid2.

    It is recommended to install a shell alias cuid for easier access:

    npx @paralleldrive/cuid2 --install
    source ~/.zshrc

    Once installed, you can use the cuid command directly. If you do not want to use the alias, use npx @paralleldrive/cuid2 instead.

    # Install shell alias (recommended)
    npx @paralleldrive/cuid2 --install
    # ✓ Alias added to .zshrc
    # Run: source ~/.zshrc
    
    # Generate a single ID
    cuid
    
    # Generate multiple IDs
    cuid 5
    
    # Generate a short slug (5 characters)
    cuid --slug
    
    # Custom length
    cuid --length 10
    
    # Custom fingerprint
    cuid --fingerprint "my-server" 2
  4. Set up the Context7 GitHub Actions workflow

    main

    To automatically update documentation after a release, create a workflow file at .github/workflows/context7-upsert.yml. This workflow uses the rennf93/upsert-context7@v1 action with the refresh operation. It is configured to trigger on release: published events and supports manual triggers via workflow_dispatch.

    name: Context7 Documentation Update
    
    on:
      release:
        types: [published]
      workflow_dispatch: # Manual trigger
    
    jobs:
      context7-upsert:
        runs-on: ubuntu-latest
    
        steps:
          - name: Checkout code
            uses: actions/checkout@v4
    
          - name: Update Context7 Documentation
            id: context7
            uses: rennf93/upsert-context7@v1
            with:
              operation: refresh
              # Token is automatically handled by the action
            continue-on-error: true
    
          - name: Check Context7 Update Result
            if: steps.context7.outputs.success == 'false'
            run: |
              echo "Context7 update failed: ${{ steps.context7.outputs.message }}"
              echo "Status code: ${{ steps.context7.outputs.status-code }}"
              exit 1
    
          - name: Show Success Result
            if: steps.context7.outputs.success == 'true'
            run: |
              echo "Context7 update successful: ${{ steps.context7.outputs.message }}"
  5. Configure Context7 documentation parsing

    main

    Create a context7.json file in the repository root to define how the codebase is parsed for documentation. You can specify project metadata, which folders to include, and which folders or file patterns to exclude (e.g., tests or node_modules).

    {
      "$schema": "https://context7.com/schema/context7.json",
      "projectTitle": "CUID2",
      "description": "Collision-resistant unique identifier generator",
      "folders": ["src"],
      "excludeFolders": ["node_modules", "tests", ".github"],
      "excludeFiles": ["*.test.js", "*.spec.js", "*.md"],
      "rules": [
        "Use Node.js best practices",
        "Maintain backward compatibility",
        "Follow semantic versioning"
      ]
    }
  6. Secure JWT Storage and Transport

    main

    To prevent XSS and data leakage, follow these storage and transport rules:

    • Avoid Local Storage: Do not store tokens in localStorage or sessionStorage as they are vulnerable to XSS. Use httpOnly, Secure, and SameSite=Strict cookies instead.
    • Avoid URLs: Never include tokens in URLs or query parameters, as they leak via logs, browser history, and the Referer header.
    • Scrub Logs: Ensure tokens are scrubbed from all logging pipelines and analytics.
    • CSRF Protection: Use SameSite=Strict or implement CSRF tokens to prevent CSRF exposure.
  7. Use ProductManager interface commands

    main

    The ProductManager interface provides several slash commands to manage product discovery, planning, and documentation. Use these commands to interact with the assistant for project setup, research, and generation:

    • /research: Chat to discover available user research or answer questions to design user journeys.
    • /setup: Initialize project metadata (name, description, domain, personas, etc.).
    • /generate [persona|journey|storymaps|userStories|feature]: Suggest items to populate your current lists.
    • /feature: Plan a specific feature from a given user story, outputting a Markdown PRD.
    • /save: Export the current project and all associated state in YAML format to $projectRoot/plan/story-map/.
    • /cancel [step]: Cancel a specific story or step.
  8. Secure Key and JWKS Handling

    main

    To prevent SSRF and key injection attacks during key retrieval:

    • Validate kid: Do not use the kid (Key ID) to fetch keys from untrusted sources. Use an allowlist of kid values.
    • Pin JWKS URLs: Do not derive JWKS URLs from the iss (issuer) claim without a strict allowlist. Pin your JWKS URLs.
    • Cache JWKS: Cache JWKS with a TTL and validate the kid against a known set.
    • Isolate Issuers: Ensure issuer key isolation. Use one keyset per issuer; never share verification keys across different issuers.
  9. Secure JWT Algorithm and Signature Verification

    main

    When implementing JWT verification, adhere to these security requirements:

    • Reject 'none' Algorithm: Never allow the none algorithm; always reject unsigned tokens.
    • Always Verify: Never use jwt.decode() without verification. Always use jwt.verify().
    • Prevent Algorithm Confusion: Do not use the alg header from the token to select the verification method. Use a strict allowlist and ensure the key type matches the expected algorithm.
    • Prefer Asymmetric Algorithms: Use asymmetric algorithms like RS256 or ES256 instead of symmetric algorithms like HS256.
  10. Configure Cookie Hardening and Token Lifetime

    main

    Apply these best practices for cookie security and token lifespan:

    • Cookie Prefixing: Use the __Host- prefix for cookies to enforce Secure, Path=/, and the absence of a Domain attribute.
    • Avoid Domain Setting: Omit the Domain attribute or use __Host- to prevent subdomain hijacking.
    • Minimize Lifetime: For stateless JWTs, the maximum recommended access token lifetime is 15 minutes. Avoid lifetimes $\ge$ 1 day.
  11. Execute an AI agent test script

    main
    To run an automated test using an AI agent, use the /run-test <script> command. The agent will attempt to drive a real browser, discover the UI visually, and follow the steps defined in the script. It will capture screenshots at checkpoints or upon failure and record difficulty, duration, and observations.
    /run-test <script>