# Sign-in keys

`POST /v1/auth/keys` trades a sign-in code for an API key that spends the user's balance;
`POST /v1/auth/keys/code` creates a code with your own API key.

## Request

These two routes end the sign-in flow. [Sign in with OpenDunes](/docs/sign-in-with-opendunes)
walks through it from the approval page to the first call.

| Route | Key | Does |
|---|---|---|
| `POST /v1/auth/keys` | no key | trades a code and its verifier for an API key |
| `POST /v1/auth/keys/code` | API key | creates a code on that key's own account, with no approval page |

A code lives 10 minutes and trades once.

### Trade a code

`POST /v1/auth/keys` takes JSON and no key: the code and its verifier are the proof.

| Field | Needed | You send |
|---|---|---|
| `code` | yes | the `code` your callback address carried, or the `id` that `POST /v1/auth/keys/code` answered |
| `code_verifier` | yes | the secret whose hash went out as `code_challenge`; with `plain`, the challenge itself |
| `code_challenge_method` | no | `S256` or `plain`, the method the challenge was made with |

The samples read the code and the verifier from the environment, as the guide's step 2 leaves
them, and print the account the new key belongs to and the start of the key. Keep the whole
key on your server, next to the user's account in your app.

```python
import json
import os
import urllib.request

ADDRESS = "https://opendunes.com/v1/auth/keys"
CODE = os.environ["OPENDUNES_AUTH_CODE"]
VERIFIER = os.environ["OPENDUNES_CODE_VERIFIER"]

body = {
    "code": CODE,
    "code_verifier": VERIFIER,
    "code_challenge_method": "S256",
}
request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(body).encode(),
    headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request) as response:
    answer = json.load(response)

print(answer["user_id"], answer["key"][:8])
```

```javascript
const ADDRESS = "https://opendunes.com/v1/auth/keys";
const CODE = process.env.OPENDUNES_AUTH_CODE;
const VERIFIER = process.env.OPENDUNES_CODE_VERIFIER;

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    code: CODE,
    code_verifier: VERIFIER,
    code_challenge_method: "S256",
  }),
});
const answer = await response.json();

console.log(answer.user_id, answer.key.slice(0, 8));
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const address = "https://opendunes.com/v1/auth/keys"

func main() {
	code := os.Getenv("OPENDUNES_AUTH_CODE")
	verifier := os.Getenv("OPENDUNES_CODE_VERIFIER")

	body, err := json.Marshal(map[string]string{
		"code":                  code,
		"code_verifier":         verifier,
		"code_challenge_method": "S256",
	})
	if err != nil {
		panic(err)
	}

	res, err := http.Post(address, "application/json", bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var answer struct {
		Key    string `json:"key"`
		UserID string `json:"user_id"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	fmt.Println(answer.UserID, answer.Key[:8])
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/auth/keys"

curl "$ADDRESS" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "'"$OPENDUNES_AUTH_CODE"'",
    "code_verifier": "'"$OPENDUNES_CODE_VERIFIER"'",
    "code_challenge_method": "S256"
  }'
```

### Create a code

`POST /v1/auth/keys/code` takes JSON and your API key. The code it answers trades for a key on
the account your key belongs to, so a tool of your own gets a key without the approval page.

| Field | Needed | You send |
|---|---|---|
| `callback_url` | yes | an `https` address, or `http` on `localhost`, `127.0.0.1` or `[::1]`; up to 2 048 characters |
| `code_challenge` | yes | the SHA-256 hash of your code verifier, in base64url; with `plain`, the verifier itself |
| `code_challenge_method` | no | `S256` or `plain`; absent, `S256` |
| `key_label` | no | the new key's name, up to 100 characters; absent, the host of `callback_url` |
| `limit` | no | the new key's cap, in DA; absent, no cap |
| `usage_limit_type` | no | when the cap starts again: `daily`, `weekly` or `monthly`, in UTC, the week from Monday; absent, never |
| `expires_at` | no | when the new key stops working, a date and time in the future; absent, never |

Yacine gives Souk Bot's order tool a key of its own, capped at 500 DA a month. The figure is
*illustrative*. Each sample makes a verifier, creates the code, and prints both as `export`
lines for the trade above.

```python
import base64
import hashlib
import json
import os
import secrets
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/auth/keys/code"
CALLBACK_URL = "http://localhost:3000/callback"

verifier = secrets.token_urlsafe(48)
digest = hashlib.sha256(verifier.encode()).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()

body = {
    "callback_url": CALLBACK_URL,
    "code_challenge": challenge,
    "code_challenge_method": "S256",
    "key_label": "Souk Bot orders",
    "limit": 500,
    "usage_limit_type": "monthly",
}
request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(body).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    code = json.load(response)["data"]["id"]

print(f'export OPENDUNES_AUTH_CODE="{code}"')
print(f'export OPENDUNES_CODE_VERIFIER="{verifier}"')
```

```javascript
import { createHash, randomBytes } from "node:crypto";

const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/auth/keys/code";
const CALLBACK_URL = "http://localhost:3000/callback";

const verifier = randomBytes(48).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    callback_url: CALLBACK_URL,
    code_challenge: challenge,
    code_challenge_method: "S256",
    key_label: "Souk Bot orders",
    limit: 500,
    usage_limit_type: "monthly",
  }),
});
const { data } = await response.json();

console.log(`export OPENDUNES_AUTH_CODE="${data.id}"`);
console.log(`export OPENDUNES_CODE_VERIFIER="${verifier}"`);
```

```go
package main

import (
	"bytes"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const (
	address     = "https://opendunes.com/v1/auth/keys/code"
	callbackURL = "http://localhost:3000/callback"
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	secret := make([]byte, 48)
	if _, err := rand.Read(secret); err != nil {
		panic(err)
	}
	verifier := base64.RawURLEncoding.EncodeToString(secret)
	hash := sha256.Sum256([]byte(verifier))
	challenge := base64.RawURLEncoding.EncodeToString(hash[:])

	body, err := json.Marshal(map[string]any{
		"callback_url":          callbackURL,
		"code_challenge":        challenge,
		"code_challenge_method": "S256",
		"key_label":             "Souk Bot orders",
		"limit":                 500,
		"usage_limit_type":      "monthly",
	})
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("POST", address, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var answer struct {
		Data struct {
			ID string `json:"id"`
		} `json:"data"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	fmt.Printf("export OPENDUNES_AUTH_CODE=%q\n", answer.Data.ID)
	fmt.Printf("export OPENDUNES_CODE_VERIFIER=%q\n", verifier)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/auth/keys/code"
CALLBACK_URL="http://localhost:3000/callback"

export OPENDUNES_CODE_VERIFIER=$(openssl rand -base64 48 \
  | tr '+/' '-_' | tr -d '=\n')
CODE_CHALLENGE=$(printf '%s' "$OPENDUNES_CODE_VERIFIER" \
  | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=\n')

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "callback_url": "'"$CALLBACK_URL"'",
    "code_challenge": "'"$CODE_CHALLENGE"'",
    "code_challenge_method": "S256",
    "key_label": "Souk Bot orders",
    "limit": 500,
    "usage_limit_type": "monthly"
  }'
```

## Response

`POST /v1/auth/keys` answers `200 OK`. The new key carries the name, the cap and the end date
the code was made with; on the approval page, the user sets its cap.

| Field | Holds |
|---|---|
| `key` | the new key's secret, `sk-...`: answered once, and never again. It spends the balance of the account that approved |
| `user_id` | the id of that account |

`POST /v1/auth/keys/code` answers `200 OK`:

| Field | Holds |
|---|---|
| `data` | the code |
| `id` | the code itself: send it as `code` to `POST /v1/auth/keys` |
| `app_id` | `null` |
| `created_at` | when it was made, in UTC |

Both answers, *illustrative*:

```json
{
  "key": "sk-…",
  "user_id": "9d4c2e7a-1b3f-4e8d-a6c5-0f2b7d9e1a34"
}
```

```json
{
  "data": {
    "id": "Xk2pQ9…",
    "app_id": null,
    "created_at": "2026-09-29T10:30:00+00:00"
  }
}
```

## What it cost

Free. Creating a code and trading it are never charged. Every request the new key sends is
charged in DA to the balance of the account it belongs to, and to its cap.

## Errors

`error.code` carries the status, and `error.message` says why.

| Status | When |
|---|---|
| 400 | a field is missing or has the wrong type, `callback_url` is neither `https` nor `http` on your own machine, `expires_at` is in the past, the code is wrong, already traded or over 10 minutes old, the verifier does not match it; `error.metadata.errors` names the field |
| 401 | on `POST /v1/auth/keys/code`: the key is missing, wrong, disabled or expired, or it is a management key |
| 403 | on `POST /v1/auth/keys/code`: the key is kept to other addresses |
