> ## Documentation Index
> Fetch the complete documentation index at: https://docs.jelou.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Secrets

> Gerencie variáveis de ambiente criptografadas: três formas de configurá-las, acesso com ctx.env, restrições de prefixo e uso em CI.

## O que são secrets?

Secrets são variáveis de ambiente criptografadas que você acessa em tempo de execução através de `ctx.env`. Use-os para chaves de API, URLs de banco de dados, tokens de serviços externos e quaisquer valores sensíveis.

## Configure secrets

Você tem três formas de configurar secrets com o CLI:

<Tabs>
  <Tab title="Inline">
    Passe pares `KEY=VALUE` diretamente:

    ```bash theme={null}
    jelou secrets set query-customer CRM_API_KEY=sk_test_EXAMPLE JELOU_API_KEY=jfn_pat_EXAMPLE
    # ✓ Set 2 secrets
    ```
  </Tab>

  <Tab title="Arquivo .env">
    Importe de um arquivo `.env`:

    ```bash theme={null}
    jelou secrets set query-customer --from-env .env.production
    ```

    O arquivo segue o formato padrão:

    ```bash .env.production theme={null}
    CRM_API_KEY=sk_test_EXAMPLE
    JELOU_API_KEY=jfn_pat_EXAMPLE
    DATABASE_URL=postgres://user:pass@host:5432/db
    ```

    Linhas em branco e comentários (`#`) são ignorados.
  </Tab>

  <Tab title="Interativo">
    Sem argumentos, o CLI guia você passo a passo:

    ```bash theme={null}
    jelou secrets set query-customer
    # ? Secret key: CRM_API_KEY
    # ? Secret value: ****
    # ? Add another secret? (y/N) y
    # ? Secret key: JELOU_API_KEY
    # ? Secret value: ****
    # ? Add another secret? (y/N) n
    # ✓ Set 2 secrets
    ```

    Os valores são mascarados durante a entrada.
  </Tab>
</Tabs>

As chaves devem estar em `UPPER_SNAKE_CASE` (padrão: `^[A-Z][A-Z0-9_]*$`).

## Acesse secrets na sua função

Use `ctx.env` dentro do handler:

```typescript index.ts theme={null}
import { define, z } from "@jelou/functions";

export default define({
  name: "send-whatsapp",
  description: "Sends a WhatsApp message using the Jelou API",
  input: z.object({
    phone: z.string().min(10),
    message: z.string().min(1),
  }),
  handler: async (input, ctx) => {
    const apiKey = ctx.env.get("JELOU_API_KEY");
    const botId = ctx.env.get("BOT_ID");

    if (!apiKey) {
      ctx.log("Error: JELOU_API_KEY not configured");
      return { sent: false, error: "Missing API key" };
    }

    const res = await fetch("https://api.jelou.ai/v1/messages/send", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        botId,
        phone: input.phone,
        message: input.message,
      }),
    });

    return { sent: res.ok, status: res.status };
  },
});
```

### Métodos de `ctx.env`

| Método               | Retorna                  | Descrição                          |
| -------------------- | ------------------------ | ---------------------------------- |
| `ctx.env.get("KEY")` | `string \| undefined`    | Obtém o valor de um secret         |
| `ctx.env.has("KEY")` | `boolean`                | Verifica se um secret existe       |
| `ctx.env.toObject()` | `Record<string, string>` | Obtém todos os secrets como objeto |

## Variáveis bloqueadas

Variáveis internas da plataforma com o prefixo `__FN_` são bloqueadas. Chamar `ctx.env.get("__FN_COMPANY_ID")` retorna `undefined`.

## Desenvolvimento local

No desenvolvimento local, o servidor `jelou functions dev` carrega secrets do seu arquivo `.env`:

```bash .env theme={null}
CRM_API_KEY=sk-test-local123
JELOU_API_KEY=jfn_pat_test_local
DATABASE_URL=postgres://localhost:5432/mydb
```

Você pode especificar um arquivo diferente:

```bash theme={null}
jelou functions dev --env .env.local
```

<Warning>
  Nunca faça commit do seu arquivo `.env` no repositório. O `jelou functions init` o adiciona automaticamente ao `.gitignore`.
</Warning>

## Listar e deletar secrets

```bash theme={null}
jelou secrets list query-customer
# ▸ Key              Updated
# ▸ CRM_API_KEY      2 hours ago
# ▸ JELOU_API_KEY    3 days ago

jelou secrets delete query-customer CRM_API_KEY
# ✓ Deleted CRM_API_KEY
```

## Secrets em CI/CD

Em pipelines de CI, use variáveis de ambiente do sistema para injetar secrets:

```yaml deploy.yml theme={null}
- name: Configure secrets and deploy
  env:
    JELOU_TOKEN: ${{ secrets.JELOU_TOKEN }}
  run: |
    jelou secrets set query-customer \
      CRM_API_KEY=${{ secrets.CRM_API_KEY }} \
      JELOU_API_KEY=${{ secrets.JELOU_API_KEY }}
    jelou functions deploy --no-confirm
```
