rules:
  - id: auth.secret.public-env-secret
    languages:
      - javascript
      - typescript
    severity: ERROR
    message: |
      A secret is being read from an environment variable whose name carries a
      client-public prefix. Bundlers inline these variables into the browser
      JavaScript at build time:

        - Next.js / webpack:        NEXT_PUBLIC_*
        - Create React App:         REACT_APP_*
        - Gatsby:                   GATSBY_*
        - SvelteKit / generic:      PUBLIC_*
        - Vite:                     VITE_*  (via import.meta.env)

      Anything carried by such a variable ships to every visitor. A secret,
      token, password, or private key placed here is published, not protected.

      Keep the secret in a server-only variable (no public prefix) and read it
      only in server code (API routes, server actions, loaders). If a value is
      genuinely safe to expose (publishable key, client_id), name it so.
    # We deliberately match only the suffixes that are NEVER legitimately
    # public: SECRET, PASSWORD, PRIVATE(_KEY). `API_KEY` / `TOKEN` are
    # excluded on purpose: many services ship *publishable* client keys and
    # public tokens under a public prefix (Stripe publishable key, Mapbox
    # token, Algolia search key, Inkeep widget key), so flagging those would
    # be a false positive on legitimate code. The trade-off is recall on a
    # genuinely-secret `NEXT_PUBLIC_*_API_KEY`; precision wins here.
    pattern-either:
      # process.env.<PUBLIC_PREFIX>...<SECRET_SUFFIX>
      - patterns:
          - pattern: process.env.$VAR
          - metavariable-regex:
              metavariable: $VAR
              regex: ^(NEXT_PUBLIC|REACT_APP|GATSBY|PUBLIC)_.*(SECRET|PRIVATE|PASSWORD).*$
      # import.meta.env.<VITE_PREFIX>...<SECRET_SUFFIX>
      - patterns:
          - pattern: import.meta.env.$VAR
          - metavariable-regex:
              metavariable: $VAR
              regex: ^VITE_.*(SECRET|PRIVATE|PASSWORD).*$
    metadata:
      oauthlint-rule-id: AUTH-SECRET-002
      oauthlint-doc-url: https://oauthlint.dev/rules/secret-public-env-secret
      category: security
      cwe: CWE-200
      owasp: A02:2021
      llm-prevalence: HIGH
      technology:
        - next.js
        - vite
        - create-react-app
      references:
        - https://nextjs.org/docs/app/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser
        - https://vitejs.dev/guide/env-and-mode#env-variables
        - https://owasp.org/Top10/A02_2021-Cryptographic_Failures/
