Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,10 @@ RANJIT_SANTANDER_KEY_FILE=./secrets/santander-key.pem
# Exactly 4 branch digits, a dot, then 12 account digits (including check digit).
RANJIT_SANTANDER_ACCOUNT=
RANJIT_SANTANDER_LOOKBACK_DAYS=7

# Optional backend notifications (HTTPS; HTTP only on loopback).
# RANJIT_WEBHOOK_URL=https://your-backend.example/webhooks/ranjit
# RANJIT_WEBHOOK_SECRET=
# Keep the previous API key temporarily while updating backend clients.
# RANJIT_API_KEY_PREVIOUS=
# RANJIT_API_KEY_PREVIOUS_EXPIRES_AT=2026-11-09T12:00:00Z
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ GO ?= go
VERSION ?= dev

-include .env
export RANJIT_API_KEY_PREVIOUS RANJIT_API_KEY_PREVIOUS_EXPIRES_AT RANJIT_WEBHOOK_URL RANJIT_WEBHOOK_SECRET
export RANJIT_API_KEY RANJIT_ADDR RANJIT_BASE_URL RANJIT_DATABASE RANJIT_PROVIDER RANJIT_SYNC_INTERVAL
export RANJIT_EFI_ENV RANJIT_EFI_CLIENT_ID RANJIT_EFI_CLIENT_SECRET_FILE RANJIT_EFI_CERT_FILE RANJIT_EFI_KEY_FILE RANJIT_EFI_LOOKBACK_DAYS
export RANJIT_INTER_ENV RANJIT_INTER_CLIENT_ID RANJIT_INTER_CLIENT_SECRET_FILE RANJIT_INTER_CERT_FILE RANJIT_INTER_KEY_FILE RANJIT_INTER_ACCOUNT RANJIT_INTER_LOOKBACK_DAYS
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ As integrações diretas usam as credenciais da aplicação criada pelo titular
Para começar localmente, instale o binário abaixo, rode `ranjit serve` e obtenha a chave com `ranjit key`. No seu backend:

```sh
go get github.com/getcortexlabs/ranjit@v0.3.0
go get github.com/getcortexlabs/ranjit@v0.4.0
export RANJIT_URL=http://localhost:8080
# Configure RANJIT_API_KEY com a chave da sua instalação.
```
Expand All @@ -37,6 +37,8 @@ O SDK é um cliente HTTP: o Ranjit roda como processo separado do seu backend. A

O [exemplo de backend Go](examples/backend/) importa um CSV e consulta transações sem precisar de acesso bancário. O [guia de instalação em servidor e Orbit](docs/server.md) cobre PostgreSQL, segredos e a configuração do SDK. O painel e os comandos locais continuam disponíveis como ferramentas de apoio.

Para repetir uma criação sem duplicar conexões, use `client.ConnectWithKey`. Webhooks assinados avisam quando a sincronização conclui ou falha definitivamente. A chave da API pode ser trocada com um prazo para migrar os consumidores. O [guia de integração confiável](docs/backend-reliability.md) traz configuração, exemplos e recuperação de falhas.

## Instalar

macOS e Linux, sem Go e sem Docker:
Expand Down Expand Up @@ -210,13 +212,15 @@ O [exemplo Go](examples/connect/main.go) mostra o fluxo completo. O contrato HTT
| `GET` | `/v1/connections/{id}` | Consultar estado e última sincronização |
| `POST` | `/v1/connections/{id}/sync` | Enfileirar sincronização |
| `GET` | `/v1/jobs/{id}` | Acompanhar execução e tentativas |
| `GET` | `/v1/webhooks/deliveries` | Inspecionar notificações e tentativas |
| `POST` | `/v1/webhooks/deliveries/{id}/retry` | Reenviar notificação que falhou |
| `GET` | `/v1/connections/{id}/accounts` | Consultar contas e saldos |
| `GET` | `/v1/accounts/{id}/transactions` | Consultar transações |
| `DELETE` | `/v1/connections/{id}` | Revogar e remover dados normalizados |

## Decisões do projeto

Um binário, um banco e um worker. `net/http` faz o transporte; SQLite ou PostgreSQL guarda os dados e a fila; o provedor só entrega lotes normalizados. O painel usa HTML, CSS e JavaScript embutidos no executável, sem etapa de build do frontend. Não há Redis, ORM ou framework web. O driver SQLite funciona sem CGO.
Um binário, um banco e workers para sincronização e notificações. `net/http` faz o transporte; SQLite ou PostgreSQL guarda os dados e a fila; o provedor só entrega lotes normalizados. O painel usa HTML, CSS e JavaScript embutidos no executável, sem etapa de build do frontend. Não há Redis, ORM ou framework web. O driver SQLite funciona sem CGO.

Os valores monetários usam centavos inteiros. As importações são atômicas e fazem upsert por identificador estável do provedor. As respostas de leitura já recebidas ficam temporariamente no banco de dados, vinculadas ao job. A retomada mantém o período solicitado e reaproveita essas respostas; tokens e headers não entram nesse armazenamento. Os registros temporários são removidos ao concluir, falhar definitivamente, expirar ou revogar. O resultado de uma tentativa antiga é rejeitado, mesmo se chegar depois da nova tentativa.

Expand All @@ -233,6 +237,6 @@ make build # bin/ranjit, sem CGO

Os testes usam SQLite em diretórios temporários e exercitam os handlers HTTP reais com transporte em memória. Cobrem consentimento, autenticação, paginação, isolamento dos IDs entre conexões, rollback, repetição de sincronização, concorrência, expiração e retomada após reinício.

Antes de operar fora da máquina local, leia [operação](docs/operations.md). A versão atual tem uma chave por instalação e banco sem criptografia em repouso. A configuração pessoal admite vários perfis; cada perfil direto acessa a conta vinculada às suas credenciais. O modo legado por variáveis de ambiente seleciona um provedor por processo. Webhooks, múltiplos operadores, outros produtos bancários e PostgreSQL ficam para mudanças com casos de uso definidos.
Antes de operar fora da máquina local, leia [operação](docs/operations.md). A versão atual tem um operador por instalação e permite trocar a chave com um período de sobreposição. O banco não tem criptografia em repouso. A configuração pessoal admite vários perfis; cada perfil direto acessa a conta vinculada às suas credenciais. O modo legado por variáveis de ambiente seleciona um provedor por processo. PostgreSQL, webhooks e idempotência estão disponíveis. Múltiplos operadores e outros produtos bancários ficam para mudanças com casos de uso definidos.

Contribuições: [CONTRIBUTING.md](CONTRIBUTING.md). Licença: [MIT](LICENSE).
30 changes: 30 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ func pageQuery(cursor string, limit int) url.Values {
}

func (c *Client) do(ctx context.Context, method, path string, input, output any) error {
return c.doWithKey(ctx, method, path, input, output, "")
}

func (c *Client) doWithKey(ctx context.Context, method, path string, input, output any, key string) error {
var body io.Reader
if input != nil {
data, err := json.Marshal(input)
Expand All @@ -210,6 +214,9 @@ func (c *Client) do(ctx context.Context, method, path string, input, output any)
if input != nil {
req.Header.Set("Content-Type", "application/json")
}
if key != "" {
req.Header.Set("Idempotency-Key", key)
}
return c.send(req, output)
}

Expand Down Expand Up @@ -237,3 +244,26 @@ func (c *Client) send(req *http.Request, output any) error {
}
return decoder.Decode(output)
}

// ConnectWithKey retries a logical creation safely for 24 hours. Persist a random
// key per operation in your backend and reuse it with the same request on retry.
func (c *Client) ConnectWithKey(ctx context.Context, input ConnectRequest, key string) (ConnectResponse, error) {
var out ConnectResponse
if !ValidIdempotencyKey(key) {
return out, fmt.Errorf("%w: invalid idempotency key", ErrInvalid)
}
err := c.doWithKey(ctx, http.MethodPost, "/v1/connections", input, &out, key)
return out, err
}

func ValidIdempotencyKey(key string) bool {
if len(key) < 16 || len(key) > 128 {
return false
}
for _, c := range key {
if c < 33 || c > 126 {
return false
}
}
return true
}
8 changes: 7 additions & 1 deletion cmd/ranjit/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Outros comandos:
ranjit validate perfil Testar acesso e gerar relatório local
ranjit revoke ID Revogar conexão e apagar seus dados
ranjit key Mostrar chave da API local
ranjit key rotate --grace 24h Trocar chave com prazo para migração
ranjit version Mostrar versão
ranjit init Gerar .env para o fluxo com Make/Docker

Expand Down Expand Up @@ -80,7 +81,12 @@ func (c cli) command(ctx context.Context, args []string) error {
return c.doctor(ctx, args[1:])
case "import":
return c.importFile(ctx, args[1:])
case "status", "accounts", "transactions", "key", "revoke":
case "key":
if len(args) > 1 && args[1] == "rotate" {
return c.rotateKey(args[2:])
}
return c.inspect(ctx, "key", args[1:])
case "status", "accounts", "transactions", "revoke":
return c.inspect(ctx, args[0], args[1:])
case "sync", "demo":
return c.sync(ctx, args[0], args[1:])
Expand Down
47 changes: 47 additions & 0 deletions cmd/ranjit/key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"crypto/rand"
"errors"
"fmt"
"time"

"github.com/getcortexlabs/ranjit/internal/config"
)

func (c cli) rotateKey(args []string) error {
f := c.flags("key rotate")
grace := f.Duration("grace", 24*time.Hour, "tempo para a chave anterior continuar válida (0 a 168h)")
if err := f.Parse(args); err != nil {
return err
}
if f.NArg() != 0 || *grace < 0 || *grace > 7*24*time.Hour {
return errors.New("use ranjit key rotate [--grace 24h]; máximo 168h")
}
cfg, err := localConfig(false)
if err != nil {
return err
}
if cfg.PersonalFile == "" {
return errors.New("configuração por ambiente: defina RANJIT_API_KEY_PREVIOUS e RANJIT_API_KEY_PREVIOUS_EXPIRES_AT, troque RANJIT_API_KEY e recrie o serviço")
}
p, err := config.ReadPersonal(cfg.PersonalFile)
if err != nil {
return err
}
now := time.Now().UTC()
if p.PreviousAPIKeyExpiresAt.After(now) && *grace > 0 {
return errors.New("há uma troca em andamento; aguarde a expiração ou use --grace 0 para invalidar as chaves anteriores")
}
p.PreviousAPIKey, p.PreviousAPIKeyExpiresAt = "", time.Time{}
if *grace > 0 {
p.PreviousAPIKey, p.PreviousAPIKeyExpiresAt = p.APIKey, now.Add(*grace)
}
p.APIKey = rand.Text() + rand.Text()
if err = config.SavePersonal(cfg.PersonalFile, p); err != nil {
return err
}
// stdout contains only the new key, so it can be redirected to a secret file.
_, err = fmt.Fprintln(c.out, p.APIKey)
return err
}
47 changes: 47 additions & 0 deletions cmd/ranjit/key_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"bytes"
"context"
"path/filepath"
"strings"
"testing"
"time"

"github.com/getcortexlabs/ranjit/internal/config"
)

func TestRotatePersonalKeyAndEndGrace(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.json")
t.Setenv("RANJIT_CONFIG", path)
t.Setenv("RANJIT_API_KEY", "")
t.Setenv("RANJIT_DATABASE_URL", "")
t.Setenv("RANJIT_PROFILES_JSON", "")
// Personal mode bypasses environment loading, including profile overrides.
p := config.NewPersonal()
if err := config.SavePersonal(path, p); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
c := cli{out: &out}
if err := c.command(context.Background(), []string{"key", "rotate", "--grace", "1h"}); err != nil {
t.Fatal(err)
}
rotated, err := config.ReadPersonal(path)
if err != nil {
t.Fatal(err)
}
if rotated.APIKey == p.APIKey || rotated.PreviousAPIKey != p.APIKey || !rotated.PreviousAPIKeyExpiresAt.After(time.Now()) || strings.TrimSpace(out.String()) != rotated.APIKey {
t.Fatal("bad rotation")
}
if err = c.command(t.Context(), []string{"key", "rotate"}); err == nil {
t.Fatal("in-flight grace replaced")
}
if err = c.command(t.Context(), []string{"key", "rotate", "--grace", "0"}); err != nil {
t.Fatal(err)
}
rotated, err = config.ReadPersonal(path)
if err != nil || rotated.PreviousAPIKey != "" || !rotated.PreviousAPIKeyExpiresAt.IsZero() {
t.Fatal("old key retained", err)
}
}
12 changes: 11 additions & 1 deletion cmd/ranjit/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/getcortexlabs/ranjit/internal/httpapi"
"github.com/getcortexlabs/ranjit/internal/service"
"github.com/getcortexlabs/ranjit/internal/store"
"github.com/getcortexlabs/ranjit/internal/webhook"
"github.com/getcortexlabs/ranjit/internal/worker"
)

Expand Down Expand Up @@ -119,8 +120,9 @@ func run(logger *slog.Logger) error {
logger.Warn("certificate needs attention", "profile", cert.Profile, "status", cert.Level, "days_remaining", cert.DaysRemaining)
}
}
db.EnableWebhooks(cfg.WebhookURL)
svc := service.New(db, source, cfg.BaseURL)
server := &http.Server{Addr: cfg.Addr, Handler: httpapi.New(svc, cfg.APIKey, logger, httpapi.Diagnostics(func() any {
server := &http.Server{Addr: cfg.Addr, Handler: httpapi.New(svc, cfg.APIKey, logger, httpapi.APIKeys(cfg.APIKeys), httpapi.Diagnostics(func() any {
return map[string]any{"version": version, "certificates": cfg.Certificates(time.Now()), "unavailable_profiles": unavailable}
})), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10}
listener, err := net.Listen("tcp", cfg.Addr)
Expand All @@ -131,6 +133,14 @@ func run(logger *slog.Logger) error {
defer cancelWorker()
workerDone := make(chan struct{})
go func() { defer close(workerDone); worker.New(db, source, cfg.SyncInterval, logger).Run(workerCtx) }()
webhookDone := make(chan struct{})
go func() {
defer close(webhookDone)
if cfg.WebhookURL != "" {
webhook.New(db, cfg.WebhookURL, cfg.WebhookSecret, logger).Run(workerCtx)
}
}()
defer func() { cancelWorker(); <-webhookDone }()
serveErr := make(chan error, 1)
go func() { serveErr <- server.Serve(listener) }()
if ui {
Expand Down
1 change: 1 addition & 0 deletions cmd/ranjit/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ func (c cli) sync(ctx context.Context, command string, args []string) error {
return err
}
defer db.Close()
db.EnableWebhooks(cfg.WebhookURL)
svc := service.New(db, source, cfg.BaseURL)
connections, err := allConnections(ctx, db)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion compose.quick.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
services:
ranjit:
image: ghcr.io/getcortexlabs/ranjit:v0.3.0
image: ghcr.io/getcortexlabs/ranjit:v0.4.0
pull_policy: never
ports:
- "127.0.0.1:8080:8080"
Expand Down
10 changes: 9 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Nos conectores diretos, `institution_id` é o nome do provedor selecionado: `efi

`POST /v1/connections` recebe `customer_id` e `institution_id`. O primeiro é o ID interno da aplicação, com até 128 bytes. Use um identificador opaco. O segundo deve vir de `GET /v1/institutions`.

No sandbox, a resposta 201 contém `connection`, `authorization_url` e `authorization_expires_at`. O link é uma credencial temporária. Apenas a aplicação que criou a conexão e a pessoa autorizando devem recebê-lo. A criação não é idempotente: não repita automaticamente um POST cujo resultado ficou incerto; consulte as conexões do cliente antes de tentar novamente.
No sandbox, a resposta 201 contém `connection`, `authorization_url` e `authorization_expires_at`. O link é uma credencial temporária. Apenas a aplicação que criou a conexão e a pessoa autorizando devem recebê-lo. Envie `Idempotency-Key` (16–128 caracteres ASCII visíveis, sem espaços) para recuperar a mesma conexão em pedidos repetidos durante 24 horas. Outro conteúdo com a mesma chave retorna `409 idempotency_conflict`. Sem a chave, cada POST cria outra conexão. Veja o [contrato de repetição e recuperação do link](backend-reliability.md).

`GET /sandbox/authorize?token=...` exibe a decisão. `POST /sandbox/authorize` recebe `token` e `decision=approve|deny` como `application/x-www-form-urlencoded`. O token dispensa a chave da API apenas nessa rota. Uma decisão bem-sucedida retorna a conexão em JSON. Reutilizar ou deixar vencer o link resulta em 410.

Expand Down Expand Up @@ -82,6 +82,8 @@ Conexões diretas em `paused` ou `expired` permitem consultar o histórico, mas
| 403 | `invalid_origin` | Origem do POST de autorização difere da URL configurada |
| 404 | `not_found` | Recurso inexistente |
| 409 | `inactive_connection` | Conexão sem consentimento ativo |
| 409 | `idempotency_conflict` | Chave de repetição usada com outro pedido |
| 409 | `webhook_not_retryable` | Entrega não está em falha ou pertence a outro destino |
| 410 | `invalid_authorization` | Token inválido, consumido ou vencido |
| 502 | `provider_credentials` | Credenciais, escopos ou vínculo da aplicação inválidos |
| 502 | `provider_unavailable` | Banco temporariamente indisponível |
Expand Down Expand Up @@ -109,3 +111,9 @@ CSV aceita `delimiter` (`,` / `;` / `tab`), `date_column`, `description_column`,
`GET /v1/transactions?customer_id=personal&q=mercado&from=2026-11-01&through=2026-11-30` busca em todas as contas desse agrupamento; `account_id` restringe uma conta. Datas são inclusivas. A busca textual trata `%` e `_` como caracteres comuns; a conversão de caixa do SQLite é limitada a ASCII. A ordenação é por `posted_on` e ID, decrescente, com `limit` e `cursor`.

`GET /v1/diagnostics` informa versão, perfis indisponíveis e validade de certificados. Não retorna caminhos, sujeitos dos certificados ou credenciais. A rota existe no servidor do binário; bibliotecas que montam seu próprio handler podem fornecê-la com `httpapi.Diagnostics`.

## Notificações e rotação

`GET /v1/webhooks/deliveries` lista eventos da URL configurada com a paginação padrão. `POST /v1/webhooks/deliveries/{id}/retry` reenfileira uma entrega em `failed` e responde `202`, sem corpo. O SDK oferece `WebhookDeliveries`, `RetryWebhook` e `VerifyWebhook`.

A assinatura, os prazos de repetição e a troca de chave com sobreposição estão no [guia de integração confiável](backend-reliability.md). Esses recursos usam o mesmo banco e não exigem serviços adicionais. A revogação também apaga as entregas da conexão, sem desfazer requisições já enviadas.
Loading
Loading