# Installation


## Installation

The SDK (`@kronbase/client`), the CLI and the Docker images are downloaded from the Kronbase registry (`registry.kronbase.dev`) with a personal token. They are not in the public npm registry, so `npm install @kronbase/client` without configuring the registry fails with a 404.

### 1. Create your token

In the dashboard, open **Package access** and press **Create token**. The token (`kbp_…`) is shown only once: copy it. It expires after a year and you can revoke it at any time from the same page. It is personal: do not share it or commit it to a repository.

What you can download depends on your plan: every plan includes the CLI, the SDKs and the local stack; BYOC images belong to the Enterprise plan.

### 2. Configure npm (once per machine)

**~/.npmrc**

```bash
echo "@kronbase:registry=https://registry.kronbase.dev/npm/" >> ~/.npmrc
echo "//registry.kronbase.dev/npm/:_authToken=YOUR_TOKEN" >> ~/.npmrc
```

### 3. Install the SDK

```bash
npm install @kronbase/client
# or, if you also use Next.js:
npm install @kronbase/client @kronbase/ssr
```

### 4. Install the CLI (optional, for local development)

```bash
npm install -g @kronbase/cli

# set up Docker (and npm, if you have not yet) with your token
kronbase registry login

kronbase start
```

`kronbase registry login` asks for the token (or reads it from `--token` or standard input), signs Docker in to `registry.kronbase.dev` and adds the `~/.npmrc` lines without duplicating them. To do it by hand:

```bash
echo "YOUR_TOKEN" | docker login registry.kronbase.dev -u kronbase --password-stdin
```

> **Note:** If you installed before with a GitHub token (`npm.pkg.github.com` and `ghcr.io`), switch to your Kronbase token: that shared access will be retired. The next time you run `kronbase start`, the CLI moves the images in your `.kronbase/.env` to the Kronbase registry on its own.


---

# CLI


## CLI

`@kronbase/cli` spins up a complete local stack (API, dashboard, Oracle, Mailpit, storage) and manages schema migrations and email templates — against that local stack or against a real project (`prod`, or a customer's dedicated deployment). See the "Installation" section to create your token and set up the Kronbase registry before installing it.

### Local stack

```bash
kronbase start              # start the local stack (no login — see Note)
kronbase status              # show services + connection info
kronbase logs [service] -f  # follow logs (all, or a single service)
kronbase stop                # stop (keeps the data)
kronbase restart [service]  # restart (all, or a single service)
kronbase destroy             # remove everything, including data — irreversible
```

> **Note:** The local stack does not ask for login — on startup, `kronbase start` directly prints a pair of API keys (`anon`, prefixed `kb_anon_`, and `service_role`, prefixed `kb_service_`) for a single, already-created project, ready to paste into your `.env.local`.

> **Access from another machine:** by default the local stack's dashboard works when opened through `localhost`, `127.0.0.1` or your local network IP (e.g. `http://192.168.1.20:3100`), with no configuration. If you open it through a hostname, over `http` the browser does not send the `Sec-Fetch-Site` header, so the CSRF protection compares the `Origin` header with the list of allowed origins and answers 403 to anything not on it. `DASHBOARD_ORIGIN` is optional: if you define it in `.kronbase/.env` (the full list, comma-separated), that list rules and access by IP is turned off, so also include `localhost` and any IP you use. Run `kronbase start` again (it recreates the container with the new variable; `kronbase restart` does not apply it):
>
> ```bash
> DASHBOARD_ORIGIN=http://localhost:3100,http://my-machine.local:3100
> ```

#### Test identity provider (`--dev-idp`)

```bash
kronbase start --dev-idp
```

Adds a **test** OpenID Connect provider to the local stack (image `ghcr.io/kronbase/dev-idp`), to try provider sign-in without real accounts or internet access. It is off by default: without the option, the stack is exactly the usual one. **Development only: do not use it in production**; it is never part of Kronbase Cloud or of a BYOC deployment.

- It listens on `http://localhost:9400` (published only on `127.0.0.1`; another port with `DEV_IDP_PORT` in `.kronbase/.env`). That is also its `issuer`, the same for the browser and for the stack's API.
- On startup, `kronbase start` prints the issuer, the fixed development credentials (`kronbase-dev-client` / `kronbase-dev-secret`), the test users and the commands to register it:

  ```bash
  kronbase auth site-url http://localhost:5173   # your app's URL
  printf '%s' 'kronbase-dev-secret' | kronbase auth provider set dev-idp --provider oidc \
    --issuer http://localhost:9400 --client-id kronbase-dev-client --client-secret-stdin --enable
  ```

- Your own users: create `.kronbase/dev-idp-users.json` (format in "Testing providers locally" in [Auth model](/en/docs#auth-model)) and run `kronbase start --dev-idp` again. The file must be readable by uid 1000 (the container's `node` user; for example mode `644`) or the service does not start.
- `kronbase start` never applies a providers file it finds in the project on its own: if `.kronbase/auth-providers.json` exists, it only prints the `kronbase auth providers apply <file>` command for you to run after reviewing it.
- If you later start without `--dev-idp`, `kronbase start` removes its container. `kronbase restart api` restarts it too, because it shares the API container's network.

### Package registry

```bash
kronbase registry login                 # asks for the kbp_… token
kronbase registry login --token kbp_…   # or takes it as an option
echo "kbp_…" | kronbase registry login  # or from standard input
```

Signs Docker in to `registry.kronbase.dev` and points `@kronbase` in `~/.npmrc` (or in `NPM_CONFIG_USERCONFIG`) to the Kronbase registry with your token, without duplicating lines. Create the token in the dashboard → **Package access**. `kronbase start` downloads from the same registry; if a download fails for lack of access, it points you to this command.

### kronbase.config.json

The migration/template commands need this file at the root of your project (outside `kronbase/`) to know what each target name points to:

**kronbase.config.json**

```json
{
  "migrationsDir": "kronbase/migrations",
  "targets": {
    "local": {
      "url": "http://localhost:3000",
      "project": "local",
      "auth": "none"
    },
    "prod": {
      "url": "https://api.kronbase.dev",
      "project": "your-project",
      "auth": "bearer"
    }
  }
}
```

A target with `auth: "bearer"` needs a session — run `kronbase login prod` once (it stores the token in `~/.kronbase/credentials.json`). The `local` target with `auth: "none"` doesn't need one — the local stack has no login.

### Dedicated deployment (BYOC) targets

A project that lives in your dedicated deployment does not show up on `api.kronbase.dev`: its API is the one on your VM, which has no account login. To point the CLI at it, use an `auth: "control-key"` target with your deployment's tunnel URL:

**kronbase.config.json**

```json
{
  "targets": {
    "stack": {
      "url": "https://your-deployment.example.com",
      "project": "my-project",
      "auth": "control-key"
    }
  }
}
```

The control key goes in an environment variable, never in the file: `KRONBASE_<TARGET>_CONTROL_KEY` (for the `stack` target, `KRONBASE_STACK_CONTROL_KEY`), or the name you set in `controlKeyEnv`.

```bash
export KRONBASE_STACK_CONTROL_KEY='ck_…'
kronbase migration list stack
kronbase migration apply stack
```

- **`url`:** the hostname of your deployment's Cloudflare tunnel. The CLI only uses `/platform/...` routes, the only ones the tunnel exposes. The VM's private IP only works from inside your network.
- **`project`:** the project slug as it exists in your deployment.
- **Where the control key comes from:** it is shown once when you register the deployment and ships in the stack zip (`control_key`). It is also the `CONTROL_KEY` variable of the `kronbase-api` container on your VM (`docker exec kronbase-api printenv CONTROL_KEY`). It cannot be looked up again from the dashboard.
- **Treat it as a deployment administrator credential:** it gives full access to its projects. Keep it out of the repository and out of `~/.kronbase/credentials.json`.

### Schema migrations

```bash
kronbase migration new <name>            # create a new .sql file
kronbase migration list [target]         # pending vs. applied (default: local)
kronbase migration apply [target]        # apply pending ones (--dry-run to preview)
kronbase migration repair [target]       # fix tracking without running SQL, after a partial failure
```

In files without the `--> statement-breakpoint` marker, each statement ends at a `;` at end of line. PL/SQL blocks (`CREATE [OR REPLACE] PROCEDURE`, `FUNCTION`, `PACKAGE [BODY]`, `TRIGGER`, `TYPE [BODY]`, and anonymous `DECLARE`/`BEGIN` blocks) contain internal `;`, so they end with a line holding only `/` (the SQL*Plus, SQLcl and SQL Developer convention). That line is not sent to the server:

```sql
CREATE OR REPLACE PROCEDURE p_hello AS
BEGIN
  NULL;
END p_hello;
/

CREATE INDEX ix_users_name ON users (name);
```

`--> statement-breakpoint` still works and takes precedence: if the file contains that marker, it is split only on it, and a lone `/` line at the end of a fragment is dropped (it is not sent to Oracle). A PL/SQL unit written on a single line and ending in `END;` / `END name;` closes there without needing `/`. A multi-line block waits for its `/`; if it is missing, it is only accepted at end of file or before the next `CREATE` when its last line is `END;`, otherwise `kronbase migration apply` fails before running anything, naming the file and the line where the block starts.

> **Note:** The execute endpoint accepts `CREATE [OR REPLACE] [EDITIONABLE | NONEDITIONABLE]` of `PROCEDURE`, `FUNCTION`, `PACKAGE [BODY]` and `TRIGGER` (besides tables, indexes, views and sequences). It also accepts `ALTER` of your own `TABLE`, `TRIGGER`, `VIEW`, `PROCEDURE`, `FUNCTION`, `PACKAGE`, `INDEX` and `SEQUENCE`; `ALTER USER`, `ALTER SESSION` and `ALTER SYSTEM` remain forbidden (`403`). `CREATE VIEW` requires the privilege of the same name, which the platform grants to each project on its own (see [Your project's platform schema keeps itself up to date](/en/docs/auth-model#your-projects-platform-schema-keeps-itself-up-to-date)); until then it fails with `ORA-01031`. `CREATE TYPE` and anonymous `DECLARE`/`BEGIN` blocks are split correctly, but the server rejects them with `403`.

> **Note:** Comments that precede a statement (`-- ...` and `/* ... */`) are ignored when the server decides whether to allow it, so a file may start with `-- kronbase:description ...` also with `--> statement-breakpoint`. An unterminated comment makes the statement be rejected with `403`.

#### PL/SQL compilation errors

Oracle creates a `PROCEDURE`, `FUNCTION`, `PACKAGE [BODY]` or `TRIGGER` even when it has compilation errors ("success with compilation error", `ORA-24344`), and the object only fails when it is used. So this does not go unnoticed, after each statement of that kind the server checks the object's `USER_ERRORS` in the same session: if there are errors (warnings do not count), the statement fails with `400` and code `PLSQL_COMPILATION_ERROR`, with a `details` array of `{ line, position, text }` (up to 20 entries). Views are not checked (`CREATE FORCE VIEW` exists precisely to create a view whose tables are created later), and neither are `CREATE ... IF NOT EXISTS` or an object qualified with a schema other than the project's:

```json
{
  "success": false,
  "code": "PLSQL_COMPILATION_ERROR",
  "error": "PACKAGE BODY PKG_PEDIDOS: 1 error de compilación — el objeto se creó pero no compila; corrige y vuelve a ejecutar CREATE OR REPLACE. Primer error (línea 3, columna 5): PLS-00201: identifier 'FOO' must be declared",
  "details": [{ "line": 3, "position": 5, "text": "PLS-00201: identifier 'FOO' must be declared" }]
}
```

The `error` message is in Spanish. `kronbase migration apply` prints the file, the statement number and each error as `line:column  text`, and stops like with any other failed statement: the statement is not recorded, so after fixing the file the next `apply` runs it again. The object does stay created (invalid) in the database until a fixed `CREATE OR REPLACE` replaces it.

#### Resuming a migration that failed partway

Oracle commits each DDL statement (`CREATE TABLE`, `ALTER`, `CREATE INDEX`…) as it runs and **does not undo it** if a later one fails. If a 147-statement file fails at statement 57, the previous 56 stay applied in the database. To avoid repeating them (and hitting `ORA-00955`), `kronbase migration apply` records in the `KRONBASE_MIGRATIONS` tracking table how many statements of the file were applied (`APPLIED_STATEMENTS`) and a hash of them. `kronbase migration list` shows the file as `parcial — N/M`.

Fix the problem and run `kronbase migration apply` again: it continues where it stopped.

```text
▸ Reanudando 20261101120000_esquema.sql desde la sentencia 57/147 (56 ya aplicada(s) antes)…
```

The CLI messages are in Spanish: `Reanudando … desde la sentencia 57/147` means "Resuming … from statement 57/147".

**When it resumes and when it refuses.** To avoid skipping or repeating statements, the CLI only resumes if the statements that were already applied are still identical, in the same order and positions. Whatever you change from the failed statement onward does not matter:

| Change to the file (after a failure at statement 57) | Result |
| --- | --- |
| Edit statement 57 (the one that failed) | Resumes from 57 |
| Edit, add or remove statements after 57 | Resumes from 57 |
| Edit a statement from 1 to 56 | Refuses |
| Remove a statement from 1 to 56 (for example, a generator that stopped emitting a table) | Refuses: the following ones shift position |
| Insert a statement before 57 | Refuses: the following ones shift position |
| Remove every statement from 57 onward (the file now matches what was already applied) | Runs nothing and marks the migration as complete |

`kronbase migration apply --dry-run` applies the same rule without running anything (it does not create or alter the `KRONBASE_MIGRATIONS` tracking table either): it marks the statements already applied in a previous attempt, says when a file would be marked complete without running anything and, if the real run would refuse to resume, shows the same message and exits with code 1.

When it refuses, the message explains what happened and what to do. For example (shown in its original Spanish):

```text
✖ 20261101120000_esquema.sql: no se puede reanudar.
  Qué pasa: un intento anterior aplicó 56 de 147 sentencia(s) y se detuvo (Oracle no deshace el DDL ya aplicado). Desde entonces, las primeras 56 sentencias del archivo (las que ya corrieron) cambiaron respecto del intento anterior.
  Por qué se niega: el CLI reanuda contando sentencias; con ese cambio el contador ya no coincide con lo que hay en la base y reanudar podría saltarse o repetir sentencias.
  En el archivo actual, en el punto de corte:
    [56/146] CREATE INDEX IX_PEDIDOS_CLIENTE ON PEDIDOS (CLIENTE_ID)   (última que se aplicó, según el archivo actual)
    [57/146] ALTER TABLE PEDIDOS ADD CONSTRAINT FK_PEDIDOS_CLIENTE FOREIGN KEY (CLIENTE_ID) REFERENCES CLIENTES (ID)   (la que correría ahora)
  Qué hacer:
    a) Restaura el archivo a como estaba en el intento anterior (por ejemplo con git) y vuelve a correr: kronbase migration apply prod
    b) Si ya comprobaste a mano que el estado real de la base coincide con el archivo nuevo: kronbase migration repair prod --mark-applied 20261101120000_esquema.sql
       (lo marca como aplicado sin correr SQL). Para empezar de nuevo, revierte a mano lo ya aplicado y corre: kronbase migration repair prod --mark-reverted 20261101120000_esquema.sql
```

In short: it says which file it is, how many statements were applied out of how many, that the already-applied statements changed since the previous attempt, why it refuses (to avoid skipping or repeating statements) and what to do. In this example the message says «56 de 147» and `[56/146]` because the file changed: it had 147 statements when it failed and now has one fewer (146), so the cut-off numbering uses the current total. The statements are shown with the contents of literals (`'...'` and `"..."`) replaced by `?`, so no passwords or data are printed.

The tracking table stores only a hash of what was applied, not the statements, so the message cannot say which one changed: it shows, cut to one line of about 80 characters, the statements the current file has at the cut-off point so you can compare them with what is in the database.

**What to do.**

1. **Restore the file** (for example `git checkout -- <file>`) and run `kronbase migration apply` again. It resumes from the statement that failed. If the change you wanted is valid, make it afterwards in a new migration file (`kronbase migration new`) rather than editing one that was already applied.
2. **If the new file is the right one** (for example, the generator dropped a table you had already created): check by hand in the database what was applied and what was not. If the real state already matches the new file, `kronbase migration repair <target> --mark-applied <file>` records it as applied without running SQL. If you prefer to start over, revert what was applied by hand and use `kronbase migration repair <target> --mark-reverted <file>`, which leaves it pending.

`repair` only fixes the tracking: it never runs SQL and never checks that the database matches the file.

### Upgrading: schema changes that need a data migration

The platform's automatic schema migrations (see [Your project's platform schema keeps itself up to date](/en/docs/auth-model#your-projects-platform-schema-keeps-itself-up-to-date)) **add** platform columns, privileges or tables, but they **do not migrate existing data**: your team migrates your data. The known cases so far:

| Change | What the platform adds | What you have to do |
| --- | --- | --- |
| `AUTH_PERMISSIONS.CATEGORY` (2026-11-03) | Optional `CATEGORY VARCHAR2(100)` column, empty on existing permissions | Fill it with your own `UPDATE` statements if you want a category other than the `CODE` prefix (for example, copying it from wherever your team kept the grouping). While it is empty, `category` is derived from the `CODE` prefix, so nothing breaks. Details in [Permission categories](/en/docs/auth-model#permission-categories). |

The other catalog change (the `CREATE VIEW` privilege, 2026-11-10) does not affect any data. Also, if your SQL inserts positionally into `AUTH_*` tables (`INSERT INTO AUTH_PERMISSIONS VALUES (...)`), any new column breaks it: always give the column list.

**How to find out.** Read the `CHANGELOG.md` of `@kronbase/cli` and `@kronbase/client` when you upgrade, and the **Novedades** (what's new) section of your project's **Overview** tab in the dashboard (shown in Spanish), which lists recent schema features (last 60 days) with their status.

### Pulling data from a target (`kronbase pull`)

```bash
kronbase pull <target> [--data] [--tables a,b] [--sample N] [--mask] [--dry-run] [--force] [--strict-migrations] [--allow-warnings] [-y]
```

`kronbase pull` leaves your local stack with the same schema as a target (`prod`, a dedicated deployment…) and, with `--data`, with its rows, so you can develop and test against real data. It does not sync back: there is no `push`. The `local` target cannot be the source.

> **Availability:** for now, the export (and with it `--data`) is available on dedicated deployments (BYOC); not yet on Kronbase Cloud, and the CLI says so with a clear message. On a dedicated deployment, the export has to be enabled by whoever operates the deployment; if it is not enabled, the CLI says so. The local stack's API (`kronbase start`) cannot export: uploading the dump requires an Autonomous Database.

**With migrations in the repo.** The local schema is built from your repo's migrations: the CLI reads the target's tracking table (`KRONBASE_MIGRATIONS`) and applies locally, in order, only the files the target has applied. This keeps local tracking consistent with the target's. Migrations in your repo that the target has not applied yet are not applied locally; the CLI lists them as pending. The pull stops, touching nothing, if:

- your repo is out of date with the target (a file applied there is missing from your repo, or has a different checksum): run `git pull` or, if appropriate, `kronbase migration repair`;
- the target has a half-applied file;
- your local stack has applied migrations the target does not have: recreate it (`kronbase destroy && kronbase start`) and try again.

**Base mode (repo with no migration files).** If `migrationsDir` does not exist or has no `.sql` files, the pull does a full import of the target's schema (with `--data`, the rows too; without it, structure only) and copies the target's `KRONBASE_MIGRATIONS` rows into the local database without running their SQL. When you later bring those files into the repo, `migration list` will see them as applied (if the checksum matches) and `migration apply` will not recreate the tables. If the target has no tracking (everything was created from the dashboard), the CLI warns that the schema is not in any migration and suggests creating a base migration with `kronbase migration new`.

#### Tables that no migration creates (drift)

Tables created from the dashboard ("New table") do not go through migrations. If the target has any that no migration in your repo creates, the pull imports them from the dump (with their DDL if they do not exist in your local stack yet) and lists them, with a warning to create a base migration. Drift is measured against what the migrations create, not against what your local stack already has: a second pull warns about the same tables as the first one. The CLI counts as created by migrations the tables of `CREATE TABLE`, `CREATE MATERIALIZED VIEW`, `ALTER TABLE … RENAME TO` and `RENAME a TO b`, plus any table that appears in your local stack when the migrations are applied during that same pull. A table whose name is built with dynamic SQL (`EXECUTE IMMEDIATE`) is not recognized on later pulls, once its migration was already applied: the CLI reports it as drift.

With `--strict-migrations` drift becomes an error (exit code 1), on every pull. If the drifted table is already in your local stack (for example, an earlier pull brought it), the pull stops before touching anything. Otherwise the CLI can only tell after applying the migrations locally: it stops then, with the migrations already applied and without exporting or importing any data.

#### Row-level security (RLS)

With `--data`, the export reads every row of each table, including tables with RLS. RLS policies do not travel in the dump: after the rows are loaded (and counted), the CLI reads the target's policies and recreates them in your local stack, the same way `kronbase rls apply` does, only for the tables it imported. If a local table already had a policy and the pull reloads it, the CLI removes it before loading and applies the target's policy at the end, so the local stack ends up with the same policies as the target. `--dry-run` lists the policies that would be replicated.

- If a policy cannot be replicated, the CLI shows the table and the reason. If that table has rows, the pull ends with an error (exit code 1) and the list: the data is already loaded, but the table has no RLS locally until you enable it with `kronbase rls apply`. If the table is empty, it is only a warning.
- If the target runs an older API version that cannot list its policies, the CLI warns and loads the data without RLS.
- If the target's API is older still and exports tables with RLS empty, the export finishes with warnings (`ORA-39181`) and the pull stops; with `--allow-warnings` it continues, without those tables' rows.
- If the pull fails or is interrupted after removing a local table's policy and before applying the target's, the CLI puts back the policy the local stack had; if it cannot, it tells you which tables were left without RLS.

#### Options

| Option | What it does |
| --- | --- |
| `--data` | Also brings the rows. Without it only the schema is pulled. After the rows are loaded, the identity columns (`GENERATED … AS IDENTITY`) of the imported tables are moved forward so the next local `INSERT` does not reuse an ID. |
| `--tables a,b,c` | Only those tables (requires `--data`). They must exist on the target. |
| `--sample N` | Only the first N rows of each table that Oracle returns (not ordered, and a repeat pull may not return the same ones; requires `--data`). It can leave child rows without their parent, drift tables included; the CLI says so, and the foreign keys that cannot be validated because of those orphans are re-enabled without validation (`NOVALIDATE`) and listed by the CLI. |
| `--mask` | Masks sensitive columns during import (requires `--data`; see below). |
| `--dry-run` | Shows the plan (migrations that would really be applied to the local stack, estimated drift, tables that would be emptied, what would be masked, RLS policies that would be replicated) without writing anything. |
| `--force` | Lets the pull continue when your local stack already has tables; the data import empties them (`TRUNCATE`) and reloads them. It never drops tables by itself. Without `--force` the CLI stops and says which tables would be emptied. |
| `--strict-migrations` | Fails if the target has tables that no migration creates (only applies when the repo has migrations; it may stop after applying the migrations locally, see "Tables that no migration creates"). |
| `--allow-warnings` | Imports even if the export finished with Data Pump warnings (by default it stops, since the dump may be incomplete). |
| `-y`, `--yes` | Skips the confirmation prompt. |

Auth tables (`AUTH_*`: users, password hashes, tokens and sessions) and `KRONBASE_MIGRATIONS` **never** come down with data, with or without `--mask`.

#### Masking data (`--mask`)

The per-column strategy is set in the `mask` key of `kronbase.config.json` (table → column → strategy):

```json
{
  "mask": {
    "customers": { "email": "email", "phone": "phone", "notes": "null" },
    "orders": { "reference": "keep" }
  }
}
```

Strategies: `email` (`u_<hash>@example.test`), `phone`, `name`, `hash`, `null` and `keep` (leave as is). Masking is deterministic within a pull (it uses a random salt that is discarded afterwards), so it preserves foreign keys and joins. Outputs are truncated (name 6 hex characters, `hash` 16, email 16, phone 8 digits), so distinct inputs can collide and violate a `UNIQUE` or `PRIMARY KEY` constraint. `null` cannot be used on a `NOT NULL` column (the configuration is rejected before anything starts).

`email`, `phone`, `name` and `hash` write text, so they only work on `CHAR`, `VARCHAR2`, `NCHAR` or `NVARCHAR2` columns with room for the output (`email` 31 characters, `name` 13, `hash` 16, `phone` 8). If the configuration asks for one of them on a column of another type, or one that is too short, the CLI stops before starting and names the column, its type and its length. `keep` and `null` work on any type.

Columns not listed in `mask` are detected by name (`email`, `correo`, `phone`, `telefono`, `name`, `nombre`, `apellido`, `nit`, `dpi`, `password`, `token`, `secret`…). There, if detection picks `null` for a `NOT NULL` column, it uses `hash` instead. Detection only applies to text columns with room for the output: a column such as `EMAIL_VERIFIED` (numeric) or an `EMAIL` that is too short is left uncovered and shows up in the report. Columns that are not recognized are **not** masked. At the end the CLI prints a report of what was masked (and whether it came from the config or from name detection) and of the columns with no coverage.

> **Important:** `--mask` is **not a guarantee of anonymity**. Review the report and add to `mask` whatever is missing. Also, the dump that travels from the target contains **real, unmasked data** until it is imported into your local stack; masking is applied during the import. The dump is deleted afterwards, on the target and on your machine.

#### Requirements

- **Object Storage configured on the deployment**: every export goes through it. It is needed for `--data`, for base mode (repo without migrations) and for the DDL of drift tables. In a dedicated deployment (BYOC), the instance needs its Object Storage credentials configured. Without them only the schema from the repo's migrations works: base mode stops without touching the local stack, and drift tables are not imported (the CLI warns and lists them).
- **Local stack running** (`kronbase start`) with Docker.
- **Time zone of the local image:** the time zone file of the local Oracle image must be at least as recent as the source database's; otherwise the CLI stops with a clear message before importing (Oracle rejects that import with `ORA-39405`). Update the local image if this happens.
- **Instance permissions:** if the export fails because the instance lacks permissions, the error says so; contact the deployment's administrator.

The first export or import job can take several minutes.

#### Interruptions and failures

Before loading the data, the CLI disables the triggers and foreign keys of the tables it is about to load (and the foreign keys that point to them); at the end it re-enables them, validating the foreign keys. The others (for example, those of `AUTH_*`) are not touched.

On Ctrl-C, `SIGTERM` or an error, the CLI first stops the import running in the local Oracle and then re-enables the triggers and foreign keys, puts back the RLS the local stack had, removes the masking package and deletes the local dump; the last step is deleting the remote export, which has its own 30-second limit: if the target does not answer, the CLI says it could not confirm the deletion (the dump may stay in the target's bucket until its expiry policy removes it, after 24 hours). It exits with code 130 (Ctrl-C) or 143 (`SIGTERM`). Every table whose local RLS was removed ends up with its previous policy or with the target's; if one cannot be put back, the CLI says so. The tables that were being loaded may be left half-loaded: run the pull again. A second Ctrl-C during the cleanup does not cut it short (the CLI says so and carries on); if the cleanup does not finish within 3 minutes, the CLI exits and says what may have been left undone. If the process is killed hard (for example `kill -9`), there is no cleanup: the local triggers and foreign keys stay disabled (recorded in the helper table `KB_PULL_DISABLED`) until the next pull with `--data`, which re-enables them; that pull will ask for `--force` because the local stack already has tables. The remote export on the target and the temporary dump on your machine (in the system temp directory, folder `kb-pull-…`) may also remain.

#### Known limitations

1. After a data import, plain sequences (`CREATE SEQUENCE`) are not moved forward; identity columns are.
2. Base mode (repo without migrations) is sensitive to foreign keys that point to tables that are not exported (the auth tables), to `--sample` orphans and to `--tables` (it only brings the DDL of the selected tables): such imports can fail with `ORA-02298` or `ORA-00942`. Recommended: pull with migrations in the repo. Objects created with compilation errors (`ORA-39082`) only produce a warning.
3. For now, data export is available on dedicated deployments (BYOC), not on Kronbase Cloud.

### Email templates

```bash
kronbase templates pull [target] [key]   # download templates to kronbase/email-templates/
kronbase templates push [target] [key]   # upload your local templates to the target
```

Without `[key]` it operates on all 5 templates (`invite`, `password_reset`, `otp_code`, `otp_magic_link`, `otp_combined`) at once. Each template is a `kronbase/email-templates/<key>.html` file whose first line is `<!-- subject: Subject -->`, so you can keep them in git and upload them all with one command.

`push` without `[key]` sends all templates in **one all-or-nothing request** (see `Upload templates in bulk` in `Email`): if any is invalid (missing `{{link}}`/`{{code}}`, unknown key, empty subject...) every error is listed and none is uploaded. `push [target] <key>` uploads only that template.

If the server removes something while sanitizing the HTML, `push` names it per template (for example `otp_code: el servidor quitó etiquetas: script; atributos: onclick — el archivo local no se modificó.`); if only the form changed, it says the HTML was normalized. Against an older API that does not report what was removed, the notice is generic. Your local file is never modified.

> **Note:** Bulk upload requires the target's API to include the `PUT .../email/templates` endpoint; against an older API, upload one at a time with `kronbase templates push [target] <key>`.

### Project email configuration

```bash
kronbase email config [target]                       # show the current configuration
kronbase email config prod --base-url https://app.com   # your app's URL for the links
kronbase email config prod --display-name "My App" --reply-to support@app.com
kronbase email config prod --reset-url https://app.com/new-password   # URL for the reset email only
kronbase email config prod --reset-url ""                            # removes that override
```

Without options it shows the configuration; with any option, it changes only those fields and keeps the rest. `--base-url` is your app's URL that the links in the invitation, password reset, magic link and OTP emails point to (see `Authentication`). `--invite-url`, `--reset-url`, `--magic-link-url` and `--otp-url` set a different URL for that email only; an empty value (`""`) removes the override and that email goes back to `--base-url`. The CLI validates them before sending: `https` (or `http` only for localhost), no fragment (`#`) and no credentials.

> **Note:** The per-type options require the target API to support `baseUrls` in `PUT .../email/config`; against an older API the command stops with an error before saving anything, so use only `--base-url`.

### Sign-in providers

Configure the sign-in providers (Microsoft, Google, Apple, GitHub and OIDC) of the target's project. What each one needs, the site URL and the callback URL are in [Auth model](/en/docs#auth-model).

```bash
kronbase auth providers [target]                # lists the providers, the site URL and each one's callback URL (or own redirect URI)
kronbase auth site-url https://app.com [target] # sets the site URL (without a url, shows it; --clear removes it)
kronbase auth provider set <slug> [target] ...  # creates or updates a provider
kronbase auth provider remove <slug> [target]   # deletes it
kronbase auth providers apply <file> [target]   # applies a providers file (see "Loading providers from a file")
```

The site URL is required before enabling a provider. Examples:

```bash
kronbase auth site-url https://app.com prod

# Google: the secret is read from a file (or from a pipe with --client-secret-stdin)
kronbase auth provider set google prod --provider google --client-id 1234.apps.googleusercontent.com \
  --client-secret-file ./google.secret --allowed-domain acme.com --allowed-domain acme.io --enable

# Apple: the secret is the .p8 key
kronbase auth provider set apple prod --provider apple --client-id com.acme.web \
  --team-id ABCDE12345 --key-id FGHIJ67890 --p8-file ./AuthKey_FGHIJ67890.p8

# OIDC with its own slug
pass show oidc/secret | kronbase auth provider set okta prod --provider oidc \
  --client-id abc --client-secret-stdin --issuer https://acme.okta.com --scopes "openid email profile"

# Private flow (API not exposed): own redirect URI and trusting the tenant's email (Microsoft with a specific tenant)
kronbase auth provider set microsoft prod --provider microsoft --client-id <id> --client-secret-file ./ms.secret \
  --tenant <tenant-GUID> --trust-tenant-email --link-by-email --no-allow-signup \
  --redirect-uri https://app.com/auth/microsoft/callback --enable

# Enable or disable without touching anything else
kronbase auth provider set google prod --disable
```

`provider set` options:

| Option | What it is for |
|---|---|
| `--provider <type>` | `microsoft`, `google`, `apple`, `github` or `oidc`. Required when creating; the type of an existing slug cannot be changed |
| `--client-id <id>` | The app's client ID at the provider (required when creating) |
| `--client-secret-file <path>` / `--client-secret-stdin` | Client secret, read from a file or from standard input through a pipe (an interactive terminal is not accepted). Required when creating |
| `--p8-file <path>` | Apple: the `.p8` key file (it is the secret; sent as is) |
| `--tenant <tenant>` | Microsoft: `common`, `organizations`, `consumers`, a GUID or a domain |
| `--trust-tenant-email` / `--no-trust-tenant-email` | Microsoft with a specific tenant (GUID or domain) only: treats the token's email (`email`, or the UPN with an email shape) as verified, instead of the `xms_edov` claim. You trust every administrator of the tenant, B2B guests included (see "Trusting the tenant's email" in the [Auth model](/en/docs#auth-model)). Rejected with `common`, `organizations`, `consumers`, the personal-accounts tenant or a non-Microsoft provider. Changing `--tenant` to any other value drops the stored trust (the CLI warns; pass `--trust-tenant-email` again if it still applies). `--trust-tenant-email` together with `--no-trust-tenant-email` is rejected |
| `--redirect-uri <url>` / `--clear-redirect-uri` | Sets your app's own redirect URI (private flow) or removes it; they are mutually exclusive and, with neither, the stored one is kept. Validated locally like the API (https; `http` only for localhost; no credentials or fragment; up to 2048 characters) |
| `--issuer <url>`, `--scopes <scopes>` | OIDC: issuer (`https`) and space-separated scopes (must include `openid`) |
| `--team-id <id>`, `--key-id <id>` | Apple: Team ID and Key ID |
| `--audience <id>` | Extra client ID accepted in mobile ID tokens (Google, Apple and OIDC) |
| `--allowed-domain <domain>` | Only allow emails from that domain |
| `--allowed-redirect <url>` | Redirect URL allowed after sign-in |
| `--link-by-email` / `--no-link-by-email` | Link or not to existing accounts by email |
| `--allow-signup` / `--no-allow-signup` | Allow or not creating new accounts with the provider |
| `--enable` / `--disable` | Enables or disables the provider |

- **The secret is never an argument** (it would end up in your shell history and in `ps`): only `--client-secret-file`, `--client-secret-stdin` or `--p8-file`. Updating without any of them keeps the stored secret. The CLI never prints it.
- `--audience`, `--allowed-domain` and `--allowed-redirect` are repeated, once per value (`--allowed-domain a.com --allowed-domain b.com`), and **replace** the stored list; to empty a list use the dashboard or the API.
- Lists and redirects are validated locally with the same rules as the API, before any call.
- `--enable` or `--disable` **alone** use a dedicated call that does not revalidate the configuration, so `--disable` works even if an OIDC issuer no longer answers. Combined with other options, the changes are saved first and then the provider is enabled or disabled.
- The `--issuer` of an existing OIDC provider cannot be changed (the API answers `400`): for another issuer, create a new slug.
- When it finishes, `provider set` shows what you must register exactly as shown in the provider's console: the callback URL or, with `--redirect-uri`, **the normalized value** the API stored (`https://app.com` becomes `https://app.com/`). With an own redirect URI the public callback is not used and neither the site URL nor `PUBLIC_API_URL` is needed: your backend receives `code` and `state` and calls the SDK's `completeOAuthSignIn` (see "Private flow (server to server)" in [Authentication](/en/docs#auth)).
- `kronbase auth providers` shows, per provider, the `redirect URI propia` row (and `callback URL: (no se usa: ...)`), or the `callback URL`; and for Microsoft the `trustTenantEmail` row (`sí` or `no`). If the server has no `PUBLIC_API_URL`, it warns that only providers with an own redirect URI can be enabled.
- If a dedicated deployment runs an API older than the CLI, it may silently drop `--redirect-uri` or `--trust-tenant-email` when saving. `kronbase auth provider set` detects it (the saved provider does not carry what you sent), warns you to update the deployment's API and does not print the callback registration instruction. The dashboard shows the same warning.
- With `--redirect-uri`, the allowed redirects and the site URL are not used for that provider.

#### Loading providers from a file

`kronbase auth providers apply` applies a JSON file with the site URL and the providers. The same file works for the local stack, Kronbase Cloud and a dedicated deployment: only the target changes (`local` by default, or the name of a target in `kronbase.config.json`, either `bearer` or `control-key`).

```bash
kronbase auth providers apply <file> [target] [--dry-run] [--prune [--yes]] [--update-secrets] [--fail-fast]
```

Format (field names are those of the providers admin API):

```json
{
  "siteUrl": "https://app.com",
  "providers": [
    {
      "slug": "microsoft",
      "provider": "microsoft",
      "clientId": "<client-id>",
      "clientSecret": "${MS_CLIENT_SECRET}",
      "config": { "tenant": "<tenant-GUID>", "trustTenantEmail": true },
      "redirectUri": "https://app.com/auth/microsoft/callback",
      "linkExistingByEmail": true,
      "allowSignup": false,
      "enabled": true
    },
    {
      "slug": "dev-idp",
      "provider": "oidc",
      "clientId": "<client-id>",
      "clientSecret": { "file": "secrets/dev-idp.secret" },
      "config": { "issuer": "https://idp.example.test" },
      "allowedEmailDomains": ["example.test"],
      "enabled": true
    }
  ]
}
```

The first one is Microsoft in the private flow (own redirect URI and trusting the tenant's email); the second one is a generic OIDC provider, for example a local test identity provider: replace the sample issuer with your provider's.

| Field | What it is |
|---|---|
| `siteUrl` | Site URL. A URL sets it, `null` removes it; if absent, it is left alone |
| `slug`, `provider`, `clientId` | Required in every provider. Same slug rules as `provider set` |
| `clientSecret` / `p8` | Secret (`p8` only for Apple). Required to create; see the rules below |
| `config` | Per provider: `tenant` and `trustTenantEmail` (Microsoft; `tenant` required), `issuer` (required), `scopes` and `audiences` (OIDC), `teamId` and `keyId` (required) and `audiences` (Apple), `audiences` (Google) |
| `enabled` | `true` enables, `false` disables; if absent, the current state is kept |
| `redirectUri` | Own redirect URI (private flow). A URL sets it, `null` removes it; if absent, it is kept |
| `linkExistingByEmail`, `allowSignup`, `allowedEmailDomains`, `allowedRedirects` | Like the `provider set` options; lists replace the stored one (`[]` empties it) |

Secrets:

- **They are never written in clear in the file.** `clientSecret` and `p8` only accept `"${VARIABLE}"` (the whole value; the environment variable must exist and not be blank) or `{ "file": "path" }` (path relative to the file's folder). A literal value is rejected.
- The client secret is trimmed (leading and trailing spaces and newlines); the `.p8` key is sent as is. Up to 8192 characters. With `{ "file": ... }` it must be a regular file of up to 8192 bytes (not a device or a pipe).
- The secret is only read and sent when **creating** the provider, or for all of them with `--update-secrets` (the API never returns secrets, so they cannot be compared). A provider that already exists does not need its variable or file, so `--dry-run` and runs without changes work without the secrets; the reference format is always validated. If a new provider's secret is missing (also with `--dry-run`), the plan says which variable or file is missing and nothing is written.
- Errors name the variable or the path, never the value. The CLI does not print secrets.

How it is applied:

- Before calling the API, the whole file is validated with the same rules as `provider set`: unknown fields (also inside `config`), slugs, types, tenant and `trustTenantEmail` (Microsoft with a specific tenant only), redirect URI, domains and redirects. **All** errors are reported at once, each with its path (e.g. `providers[1].config.tenant`), and nothing is written.
- Then it reads the target's state and shows the plan: `+ crear` (create), `~ actualizar (changed fields)` (update), `= sin cambios` (unchanged) and, with `--prune`, `- borrar` (delete). Only the fields the file sets are compared; the ones it omits are kept. Applying the same file twice changes nothing the second time.
- Creating a provider without a secret, changing the type of an existing slug or the `issuer` of an existing OIDC provider (use a new slug), and removing the site URL (`"siteUrl": null`) while providers would stay enabled without `redirectUri` (disable them in the file with `"enabled": false` or give them `redirectUri`) are also plan errors, and nothing is written.
- An `http://` `issuer` passes local validation (the plan warns), but the API requires `https` except for the local stack's test identity provider.
- Order: first the site URL; then each provider (changes with a `PUT` without `enabled` and, if it must be enabled, a `PATCH` afterwards; disabling is always a `PATCH`, before the other changes). A provider that is already enabled stays enabled.
- If the API rejects enabling because the site URL or `PUBLIC_API_URL` is missing, the error says so: add `siteUrl` or use `redirectUri` (private flow), which needs neither.
- `--dry-run` shows the plan and writes nothing. With `--prune --dry-run` the plan reminds you that applying it will ask for confirmation.
- Without `--prune` nothing is deleted: the target's providers that are not in the file are listed and kept. With `--prune` they are deleted, after confirming in the terminal (type `borrar`) or with `--yes`; with no terminal and no `--yes`, nothing is written.
- If a provider fails, it is reported and the others continue; `--fail-fast` stops at the first failure. A `401` stops the run.
- With a dedicated-deployment API older than the CLI, it warns like `provider set` if `redirectUri` or `trustTenantEmail` was dropped.

Exit code: `0` if everything was applied, there was nothing to change or the `--dry-run` is valid; `1` if the file or the plan is invalid, a step failed, `--prune` was not confirmed, or on an authentication or connection error.

```bash
# The same file in the three environments
kronbase auth providers apply .kronbase/auth-providers.json --dry-run
kronbase auth providers apply .kronbase/auth-providers.json            # local stack
MS_CLIENT_SECRET="$(pass show ms/secret)" kronbase auth providers apply .kronbase/auth-providers.json prod
kronbase auth providers apply .kronbase/auth-providers.json my-byoc --prune --yes
```

### Outbound webhooks

Manage the webhooks that notify your backend of events in the target's project (users, notifications). Events, signature verification and limits are in [Webhooks](/en/docs#webhooks).

```bash
kronbase webhooks list [target]                          # lists the webhooks (never shows secrets)
kronbase webhooks add <url> [target] --event user.created   # creates one; the signing secret is shown only once
kronbase webhooks remove <id> [target]                   # deletes it and its delivery log (asks for confirmation)
kronbase webhooks enable <id> [target]                   # re-enables it (resets the failure counter)
kronbase webhooks disable <id> [target]                  # disables it without deleting it
kronbase webhooks rotate-secret <id> [target]            # new signing secret (the old one stops working); shown only once
kronbase webhooks test <id> [target]                     # sends a webhook.test event and shows the response
kronbase webhooks deliveries <id> [target]               # delivery log, without the event contents
kronbase webhooks retry <endpointId> <deliveryId> [target]  # retries a failed delivery
```

`target` is `local` by default. `add` options:

| Option | Description |
|---|---|
| `--event <type>` | Event to receive; repeat it for several |
| `--events <list>` | Comma-separated events (same as repeating `--event`) |
| `--all-events` | Receives all events (`*`) |
| `--description <text>` | Description of the webhook |

Pass at least one of `--event`, `--events` or `--all-events`; the CLI rejects the command before calling the API otherwise. `remove` asks you to type `borrar` to confirm; in a non-interactive environment (CI) it requires `-y, --yes`. `deliveries` takes `--limit <n>` (default 20) and `--offset <n>` (default 0). `test` exits with code `1` if your endpoint does not answer `2xx`.

```bash
kronbase webhooks add https://api.acme.com/hooks/kronbase prod --events user.created,user.deleted
kronbase webhooks add https://api.acme.com/audit prod --all-events --description "Audit"
kronbase webhooks deliveries 9f2c prod --limit 50
```

### Row-level security

```bash
kronbase rls apply <table> --predicate "..." -t prod   # enable RLS on a table
kronbase rls list -t prod                              # active policies
kronbase rls remove <table> -t prod                    # disable the policy
```

Instead of `--predicate`, `rls apply` accepts per-operation rules: `--select`, `--insert`, `--update`, `--update-check` and `--delete` (USING / WITH CHECK, see [Database](/en/docs/database#per-operation-rules-using-with-check)). Operations you do not pass are denied to everyone except `service_role`; `--update-check` requires `--update`, and they cannot be combined with `--predicate`, `--group-column` or `--user-column`. `rls list` shows each operation's rule (or `denegado`, denied).

```bash
kronbase rls apply OVERTIME_REQUESTS -t prod \
  --select "REQUESTER_ID = current_user_id()" \
  --insert "REQUESTER_ID = current_user_id() AND APPROVED_BY IS NULL"
```

`kronbase rls sync` creates, updates and (optionally) removes policies from a JSON file (format in [Database](/en/docs/database#sync-from-a-file)); use it to change a rule without disabling RLS:

```bash
kronbase rls sync [-t <target>] [-f, --file kronbase/rls.json] [--dry-run] [--check] [--prune] [-y]
```

| Option | Description |
|---|---|
| `-f, --file <path>` | File with the policies (default `kronbase/rls.json`). |
| `--dry-run` | Shows what would change (`created`, `updated`, `unchanged`, `removed`, `error`) without writing anything. |
| `--check` | Like `--dry-run`, and exits with code 1 if there are differences. Meant for CI. |
| `--prune` | Removes RLS from tables that are not in the file. Refused if the file declares no tables. |
| `-y, --yes` | Skips the confirmation when applying to a non-`local` target. |

Exit code: `0` if everything is in sync or was applied successfully; `1` if any table reports `error` or, with `--check`, if there are differences; also if the file is unreadable or invalid, if you use `--prune` with an empty `tables`, or if the API or the connection fails. CI check example:

```bash
kronbase rls sync --check -t prod
```

`--dry-run` and `--check` validate columns and the rule read-only, but they do not grant access to tables the rule references nor try the owner column's default, so some apply-time failures cannot be predicted. With `--prune`, the simulation reports `removed` without validating.

`kronbase rls scheduler-bypass` controls whether background job-queue sessions (`DBMS_SCHEDULER`, `DBMS_JOB` and similar) that run as the project's schema user see every row of tables with RLS (by default they see 0). It only has an effect if that user has `CREATE JOB`, which you grant (dedicated deployment or local); on Kronbase Cloud it doesn't have it today. Details and risks in [Database](/en/docs/database#dbms-scheduler-jobs-and-processes-without-a-user):

```bash
kronbase rls scheduler-bypass on|off|status [-t <target>] [-y]
```

With no action it shows the state (`status`). `on` and `off` ask for confirmation on a target other than `local`, unless `-y`.

### Importing files into a bucket

`kronbase storage import` uploads a local folder to one of the project's buckets. Each file's path inside the folder becomes its path in the bucket (`./files/invoices/january.pdf` → `invoices/january.pdf`); `--prefix` puts everything inside a subfolder (`--prefix migrated` → `migrated/invoices/january.pdf`). It works the same on the shared version and on a dedicated deployment: it uploads through the project's API, which enforces permissions, quota and isolation between projects.

```bash
kronbase storage import <folder> [target] --bucket <name> [--prefix <subfolder>] [--dry-run] [--concurrency <n>] [--exclude <pattern>] [--force] [--allow-skipped] [--json]
```

The target is chosen as in `kronbase migration` (the `[target]` argument, or `-t/--target`; `local` by default) and uses the same credentials (`kronbase login` for a `bearer` target). The bucket must exist: create it first from the dashboard.

Recommended flow to migrate files that currently live somewhere else:

1. Download the files to a local folder with the tool you prefer, for example the OCI CLI (`oci os object bulk-download --bucket-name <source> --download-dir ./files`) or `rclone copy <remote>:<source> ./files`.
2. Review the plan without uploading anything: `kronbase storage import ./files prod --bucket documents --dry-run`. It shows how many files and bytes would be uploaded, the maximum size per file, the quota, the files that already exist and the ones that are skipped and why.
3. Import: `kronbase storage import ./files prod --bucket documents`.
4. Check the final report (uploaded, verified, already present, skipped, failed) and the exit code. If anything failed, run the same command again: files already in the bucket with the same size are skipped.
5. Once you have checked the result, delete the originals yourself. The command never deletes anything, neither in your folder nor in the bucket.

What it does with each file:

- **Skipped and reported:** symbolic links (never followed), system files (`.DS_Store`, `Thumbs.db`, `desktop.ini`), files or folders that cannot be read (no permission, or gone during the scan) and paths the server would reject (see "Accepted file names" in the Storage section).
- **Hidden:** files and folders starting with `.` (`.env`, `.git/`…) **are uploaded**, but the plan lists them so you can check there are no secrets. Use `--exclude` to leave them out.
- **`--exclude <pattern>`** (repeatable): simple glob with `*` (anything within a name), `**` (anything, folders included) and `?` (one character). A pattern without `/` is matched against each folder or file in the path (`--exclude .git`, `--exclude "*.tmp"`); with `/`, against the whole relative path (`--exclude "logs/**"`).
- **Too large to upload:** files over the server's maximum per file (100 MB by default) are listed before starting and are not attempted.
- **Quota:** if what needs uploading does not fit in the project's storage quota, the command warns and uploads nothing unless you pass `--force`.
- **Upload:** in parallel (`--concurrency`, 3 by default, 16 at most) and with at most 200 MB of files in flight at once (twice the server's maximum per file, at least 128 MB) (a larger file uploads on its own). Each file is retried up to 3 times with increasing waits (with some random variation) on network errors, `5xx` or `408` (upload cut off for being too slow); if the server sends `Retry-After`, it waits at least that long. When the server answers `429` (busy), the file waits as long as `Retry-After` says and tries again without using up those 3 retries, for up to 5 minutes of waiting in total. Other `4xx` errors are not retried. A failing file does not stop the others.
- **Already present:** a file that is already in the bucket with the same path and size is skipped; if the size differs, it is uploaded again and overwritten. The comparison is by size only: **a modified file that keeps exactly the same size is not uploaded again**. If the bucket has more objects than the API can list at once (50,000), the command says so and the files it could not compare are uploaded again.
- **Verification:** each upload is marked verified when the server confirms the same path and size.

Progress is shown as a counter, and errors as they happen. `--json` prints only the full, machine-readable report.

Exit codes:

- `0`: everything was uploaded or already present (system files, files excluded with `--exclude` and files already present do not count as skipped).
- `1`: some file failed to upload, or there was an error before starting (missing bucket, quota without `--force`…).
- `2`: nothing failed, but some files were not uploaded because of an invalid path, their size, being symbolic links or special files, or being unreadable. With `--allow-skipped` that case returns `0`. `--dry-run` uses the same codes for what would be uploaded.

> **Note:** Keeping subfolders, and names with spaces, accents or other Unicode characters, requires an API version that accepts the `path` field on file uploads. Against an older API, which would store each file under its name only, the command refuses to import files in subfolders (or with `--prefix`) instead of flattening them; folders without subfolders can still be imported. On a dedicated deployment, update it before importing.

### Bucket policies for the user's token

`kronbase storage policy` manages what end users can do with their own token in each bucket: upload, delete or read (see "Uploading and deleting with the user session" in Storage). It works the same on the shared version, locally and on a dedicated deployment. The target is chosen as in `storage import` (`[target]` argument or `-t/--target`; `local` by default). The bucket must exist.

```bash
kronbase storage policy list [target] [--bucket <name>] [--json]
kronbase storage policy set <bucket> <upload|delete|read> [target] --scope <own-folder|bucket> [--permission <code>]
kronbase storage policy remove <bucket> <upload|delete|read> [target] [-y]
```

List the project's policies (or only those of one bucket):

```bash
kronbase storage policy list prod --bucket avatars
```

Each user can upload only under their own folder (`<user id>/…`):

```bash
kronbase storage policy set avatars upload prod --scope own-folder
```

Only users with the `storage.admin` permission can delete any file in the bucket (`--scope bucket` requires `--permission`):

```bash
kronbase storage policy set avatars delete prod --scope bucket --permission storage.admin
```

Remove the read policy (any user with a session can read again); without `-y` it asks for confirmation:

```bash
kronbase storage policy remove avatars read prod -y
```

If the given permission does not exist in the project, the command still saves the policy and warns you: nobody will satisfy it until you create the permission. Against an API older than this feature, `list`, `set` and `remove` all fail with the same message telling you to update the instance.


---

# Authentication


## Authentication

Kronbase includes a complete auth system for the end users of your application. Sessions are stored in your Oracle schema.

### Initialize the client

```typescript
// lib/kronbase.ts
import { createClient } from '@kronbase/client'

export const kb = createClient(
  process.env.NEXT_PUBLIC_KB_URL!,   // https://api.kronbase.dev/api
  { anonKey: process.env.NEXT_PUBLIC_KB_KEY! }
)
```

### Sign up

```typescript
// signUp(email, password)
const result = await kb.auth().signUp(
  'user@example.com',
  'a-secure-password'
)
// result.user    → { id, email, createdAt, emailVerified: false }
// result.session.accessToken → JWT — the session is already valid, no extra steps
```

> **Note:** `signUp()` returns a full session right away — you don't need to verify the email to use it, and `signIn()` doesn't require it later either. `emailVerified` starts as `false` and becomes `true` when the user successfully completes an OTP code or magic link verification (see below); signing up alone doesn't change it. Neither `signUp()` nor `signIn()` require it, so it is up to you whether to use it to limit functionality in your app.

### Sign in

```typescript
// signIn(email, password)
const result = await kb.auth().signIn(
  'user@example.com',
  'a-secure-password'
)
// result → { success: true, user: { id, email } }
//       or { success: false, error, code }
// signIn() does not return the tokens: with a cookie adapter (SSR) it stores
// them in the access_token (1 hour by default) and refresh_token (30 days) cookies
```

> **Note:** Without a cookie adapter `signIn()` does not hand you the tokens. To get them call `POST /api/auth/signin` (see "Direct REST endpoints"). Protocol details (JWT, refresh, cookies, 2FA) are in the "Auth model" section (auth-model).

### Store the session and get the user

```typescript
// Store tokens in cookies (for SSR / middleware).
// `result` is the response of signUp() (or of the REST /api/auth/signin)
await kb.auth().setSession({
  accessToken:  result.session.accessToken,
  refreshToken: result.session.refreshToken,
})

// Read the current user from the cookies (no network)
const user = await kb.auth().getUser()
// user → { id, email } | null
```

### Sign out

```typescript
await kb.auth().signOut()
```

### Refresh the token

```typescript
const result = await kb.auth().refreshToken(refreshToken)
// result → { success, accessToken, refreshToken, expiresIn, expiresAt }
```

### Sign in with a provider

With the providers you enabled in your project (Microsoft, Google, Apple, GitHub or OIDC; see [Auth model](/en/docs#auth-model)) the user signs in in two steps: `signInWithOAuth` sends them to the provider and `exchangeCodeForSession` redeems the `?code=` when they come back to your app. `slug` is the provider's slug in your project (`google`, `microsoft`, `apple`, `github` or an OIDC one).

```typescript
// 1. «Continue with Google» button: generates the PKCE pair, stores the code_verifier,
//    asks the API for the URL and redirects the browser to the provider
const start = await kb.auth().signInWithOAuth('google', {
  redirectTo: 'https://app.com/auth/callback',   // optional; must be in the allowed redirects
})
// start → { success: true, url } | { success: false, error, code }
// with navigate: false it does not redirect: navigate to start.url yourself

// 2. On the page the provider returns to (arrives with ?code=...  or  ?error=...&error_description=...)
const params = new URLSearchParams(window.location.search)
const code = params.get('code')
if (code) {
  const result = await kb.auth().exchangeCodeForSession(code)
  // With a cookie adapter it stores the cookies and returns { success, user };
  // without one it also returns result.session = { accessToken, refreshToken, expiresAt }
}
```

The SDK generates the PKCE for you: the API **requires** an S256 `code_challenge` on start and the `code_verifier` on exchange, so the code is only useful to the browser or app that started the flow. The `code_verifier` is stored, in order: in the `pkceStorage` option (`getItem`/`setItem`/`removeItem`, sync or async; for example AsyncStorage in React Native) if you pass one; in an httpOnly cookie `kronbase_pkce_verifier` (10 minutes, `SameSite=Lax`, deleted after the exchange) if the client has a `cookieAdapter`, so that the exchange in a server callback reads the verifier from the same browser; in `sessionStorage`; and only with an explicit `pkceStorage: 'memory'`, in memory (single-user scripts, never multi-user servers); with none of them, `signInWithOAuth` returns `OAUTH_PKCE_STORAGE` instead of silently degrading. Only one sign-in at a time per tab is supported: a second start invalidates the first. WebCrypto is required: browsers and Node 19 or later (Node 18 only with `--experimental-global-webcrypto`).

**The verifier cookie is httpOnly only if the server writes it.** `createBrowserClient` from `@kronbase/ssr` writes cookies with `document.cookie`, where `httpOnly` does not apply: started from the browser, the verifier is as exposed to the page's JavaScript as in `sessionStorage`. For it to be httpOnly, call `signInWithOAuth` from a **server action or a route handler** with the server client (`navigate: false`, then redirect to `start.url` yourself). Do not call it from a **Server Component**: cookies are read-only there, the write fails silently and the exchange answers `OAUTH_PKCE_MISSING`. With SSR, the per-IP limits of the start and the exchange count your server's IP (see "Rate limits" in [Auth model](/en/docs#auth-model)).

Client-side errors (`code` in the result): `OAUTH_PKCE_MISSING` (on exchange there is no sign-in in progress in this browser), `OAUTH_PKCE_UNSUPPORTED` (no WebCrypto), `OAUTH_PKCE_STORAGE` (the verifier could not be stored) and `OAUTH_BAD_URL` (the server returned a URL that is not http(s)). Server errors (`OAUTH_PKCE_REQUIRED`, `OAUTH_CODE_INVALID`, `OAUTH_ACCOUNT_EXISTS`…) are in the codes table in [Auth model](/en/docs#auth-model). Remember that `redirect_to` must match an allowed redirect exactly; otherwise the browser returns to the site URL.

**Native mobile app.** If your app already gets an ID token from the provider with its own SDK, redeem it with no redirects or PKCE (not available with GitHub):

```typescript
// fresh nonce on every sign-in; the same value goes to the provider and to Kronbase
const result = await kb.auth().signInWithIdToken('apple', { idToken, nonce })
// Each ID token is accepted only once; a retry gets the generic 401 OAUTH_ID_TOKEN_INVALID
```

> **Note:** Signing in with a provider does not ask for the project's TOTP (the provider handles the second factor). The previous SDK flow read `access_token` and `refresh_token` from the return URL and stored them with `setSession`; there are no tokens in the URL anymore (see "Migrating from environment-variable configuration" in the Auth model).

### Private flow (server to server)

Meant for dedicated (BYOC) deployments whose API is **not exposed to the internet**: the provider cannot call Kronbase's public callback, so it sends the user back to **a route of your app** and **your backend** forwards `code` and `state` to Kronbase with the project API key. Only your backend reaches the API. It requires `@kronbase/client` 2.21 or later. The contract details (configuring the redirect URI, error codes, limits, Apple) are in "Private flow (server to server)" in the [Auth model](/en/docs#auth-model).

**1. Configure the provider** with an own redirect URI, for example `https://app.com/auth/microsoft/callback` ("URI de retorno propia" field in the dashboard, `kronbase auth provider set ... --redirect-uri <url>` or `redirectUri` in the API). It is stored normalized and you must register in the provider's console **exactly the stored value** (`https://app.com` becomes `https://app.com/`). With it, neither the site URL nor `PUBLIC_API_URL` is needed. In Microsoft Entra, register the redirect URI under the **Web** platform (not "Single-page application"): Kronbase exchanges the code with the client secret, from the server.

**2. Two routes in your backend** (Next.js example with the server client from [SSR](/en/docs#ssr)):

```typescript
// app/api/auth/microsoft/start/route.ts: the "Continue with Microsoft" button points here
import { NextResponse } from 'next/server'
import { createClient } from '@/lib/kronbase/server'   // the server client from the SSR section (cookieAdapter with cookies())

export async function GET() {
  const kb = await createClient()   // in private mode, build it with server-only variables (see below)
  // Generates the PKCE pair, stores the verifier in the httpOnly cookie kronbase_pkce_verifier
  // (written by the cookieAdapter) and asks for the authorization URL. It does not navigate: we redirect.
  const start = await kb.auth().signInWithOAuth('microsoft', { navigate: false })
  if (!start.success) {
    return NextResponse.redirect(new URL(`/login?error=${start.code ?? 'OAUTH_START_ERROR'}`, process.env.APP_URL!))
  }
  return NextResponse.redirect(start.url)
}
```

```typescript
// app/auth/microsoft/callback/route.ts
// This route is your own redirect URI: https://app.com/auth/microsoft/callback
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/kronbase/server'

export async function GET(req: NextRequest) {
  const q = req.nextUrl.searchParams
  const code = q.get('code')
  const state = q.get('state')
  // If the user cancelled, the provider returns with ?error=...: handle it here, without calling complete
  if (q.get('error') || !code || !state) {
    return NextResponse.redirect(new URL('/login?error=cancelled', process.env.APP_URL!))
  }

  const kb = await createClient()
  // Reads the verifier from the cookie, calls POST /auth/oauth/microsoft/complete with the API key
  // and, with a cookieAdapter, writes the access_token and refresh_token session cookies
  const result = await kb.auth().completeOAuthSignIn('microsoft', { code, state })
  if (!result.success) {
    // OAUTH_SIGNUP_DISABLED (403): the user does not exist and sign-ups are closed
    const reason = result.code === 'OAUTH_SIGNUP_DISABLED' ? 'user-not-found' : result.code ?? 'error'
    return NextResponse.redirect(new URL(`/login?error=${reason}`, process.env.APP_URL!))
  }
  return NextResponse.redirect(new URL('/dashboard', process.env.APP_URL!))
}
```

With a `cookieAdapter` (such as the one in `@kronbase/ssr/server`), `completeOAuthSignIn` sets the session cookies and **does not return `session`**; without one it returns `session` (`{ accessToken, refreshToken, expiresAt }`) for your app to store as it prefers. It **does not return `user`**: the API only delivers the tokens (`getUser()` reads the user from the token). If your app has its own session system, use it with `session` and your own `pkceStorage` (the client for that is built with `createClient` from `@kronbase/client`, not with `createServerClient` from `@kronbase/ssr`).

In private mode the server client (`lib/kronbase/server.ts`) must read the API URL and the key from **server-only variables** (for example `KB_URL` and `KB_API_KEY`, without the `NEXT_PUBLIC_` prefix) and pass them to `createServerClient`: the private API's URL must not end up in the browser bundle.

**3. What to watch for:**

- **The start must run where cookies can be written:** a Route Handler, a Server Action or a middleware (or a per-request `pkceStorage`, which needs `createClient` from `@kronbase/client`: `createServerClient` from `@kronbase/ssr` does not forward it). In a Server Component the write fails silently and `completeOAuthSignIn` answers `OAUTH_PKCE_MISSING`. The SDK does not fall back to memory: without a `cookieAdapter` or `pkceStorage` it returns `OAUTH_PKCE_STORAGE`; `pkceStorage: 'memory'` is only for single-user scripts, never for a multi-user server.
- **The user must come back in the same browser** that started the flow (the verifier cookie belongs to your domain, `SameSite=Lax`, 10 minutes), and there is **one start at a time per browser**.
- **Any failure means restarting the sign-in:** the `state` is single-use and `completeOAuthSignIn` deletes the verifier after any attempt, also on a `429` or a network error.
- If the provider comes back with `?error=...` (the user cancelled), your route handles it before calling `completeOAuthSignIn`.
- `redirect_to`, the allowed redirects and the site URL are **ignored** with an own URI: your app decides where the user goes.
- **Apple** arrives with a cross-site `POST` and the `SameSite=Lax` cookie does not travel on it; its name also does not reach Kronbase. See the limitations in the Auth model.
- On `OAUTH_SIGNUP_DISABLED` (`403`, the user does not exist and sign-ups are disabled) your app can show its own message, for example "User not found in the system".

**Raw HTTP variant (no SDK).** The same two REST calls, `GET /api/auth/oauth/<slug>?code_challenge=...` and `POST /api/auth/oauth/<slug>/complete`:

```typescript
// Without the SDK: raw HTTP. The verifier goes in your own httpOnly cookie (tie to the browser).
import { createHash, randomBytes } from 'node:crypto'
import { cookies } from 'next/headers'

const API = process.env.KB_URL!          // the API URL including /api (https://<your-api>/api), reachable only from your backend
const headers = { 'x-api-key': process.env.KB_API_KEY!, 'content-type': 'application/json' }

export async function start(): Promise<string> {
  const verifier = randomBytes(32).toString('base64url')                     // 43 PKCE characters
  const challenge = createHash('sha256').update(verifier).digest('base64url')
  const res = await fetch(`${API}/auth/oauth/microsoft?code_challenge=${challenge}&code_challenge_method=S256`, { headers })
  const body = await res.json()
  if (!body.success) throw new Error(body.code)
  const jar = await cookies()
  jar.set('kb_pkce', verifier, { httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge: 600 })
  return body.url as string                                                  // redirect the user here
}

export async function complete(code: string, state: string) {
  const jar = await cookies()
  const verifier = jar.get('kb_pkce')?.value
  jar.delete('kb_pkce')                                                      // the state is single-use
  if (!verifier) return { ok: false as const, code: 'OAUTH_PKCE_MISSING' }
  const res = await fetch(`${API}/auth/oauth/microsoft/complete`, {
    method: 'POST', headers, body: JSON.stringify({ code, state, code_verifier: verifier }),
  })
  const body = await res.json()
  if (!body.success) return { ok: false as const, code: body.code as string }
  return { ok: true as const, session: body.data as { accessToken: string; refreshToken: string; expiresAt: string } }
}
```

For Microsoft with your own company's tenant, see "Trusting the tenant's email (Microsoft)" in the Auth model.

### Passwordless OTP / Magic link

```typescript
// Send an OTP code to the email
await kb.auth().sendOtp('user@example.com', 'code')

// Or send a magic link (click → automatic login)
await kb.auth().sendOtp('user@example.com', 'magic_link')

// Verify the received code (same method)
const result = await kb.auth().verifyOtp('user@example.com', '482910')
// result → { success, user }; a successful verification sets emailVerified to true
```

### Email links (base_url and type)

These emails are written in the project's email language (see «Email language» in `Email`).

The invitation, password reset and magic link emails carry a link that points to your project's `base_url` (set in the dashboard or with `kronbase email config --base-url`). The link is:

```text
<base_url>?token=<token>&type=<type>

type = invite      → invitation
type = recovery    → password reset
type = magiclink   → magic link
```

The same token works for all three uses and the `type` parameter tells you which one it is, so with a single `base_url` (for example `https://app.com`) your app decides which screen to show. If the `base_url` already has a query string, the parameters are appended with `&`. Older links (only `?token=`) keep working.

#### A different URL per email type

If each email should lead to a different route of your app, set an override per type; a type without an override keeps using the `base_url`:

| Key | Email | Link `type` |
|---|---|---|
| `invite` | invitation | `invite` |
| `reset` | password reset | `recovery` |
| `magic_link` | magic link (`otp/send` with `type: 'magic_link'`) | `magiclink` |
| `otp` | OTP with code and link (`type: 'combined'`); the code-only email has no link | `magiclink` |

Set them with `kronbase email config --invite-url/--reset-url/--magic-link-url/--otp-url` (see `CLI`), in the dashboard, or with `PUT /platform/customers/me/projects/:id/email/config` and the `baseUrls` field:

```json
{ "baseUrl": "https://app.com", "baseUrls": { "reset": "https://app.com/account/new-password", "invite": "https://admin.app.com/accept" } }
```

- Allowed keys: `invite`, `reset`, `magic_link`, `otp`; any other answers `400`.
- Each URL must be absolute, `https` (or `http` only for `localhost`, `127.0.0.1` or `[::1]`; on the `kronbase start` local stack, any host), without spaces or control characters, without credentials (`user:password@`), without a fragment (`#...`) and up to 500 characters; otherwise `400` and nothing is saved. It is stored normalized (for example `"` becomes `%22`), so `GET` may return it with small differences in form.
- The default `baseUrl` is validated the same way (it allows a fragment, for hash-routing apps; up to 500 characters as you write it) only when you change its value. A `baseUrl` saved before this validation that does not meet it keeps working in the links, and you can edit the rest of the configuration (`displayName`, `replyTo`, `baseUrls`) by sending it back unchanged; only when you change it must it meet the rules.
- If you send `baseUrls`, it replaces every override: types you leave out (or set to `null` or `""`) go back to the `base_url`, and `baseUrls: null` or `{}` removes them all. If you do not send `baseUrls`, the saved overrides do not change.
- `GET .../email/config` returns `baseUrls` with only the configured types (`{}` when there are none). If the instance does not support overrides yet, it omits `baseUrls`, and a `PUT` that includes them answers `503`.

```typescript
// On the page that receives the link (e.g. app/page.tsx)
const params = new URLSearchParams(window.location.search)
const token = params.get('token')
const type = params.get('type')   // 'invite' | 'recovery' | 'magiclink'

if (type === 'recovery') router.push(`/reset-password?token=${token}`)
```

### TOTP (two-factor authentication)

```typescript
// 1. Start setup — returns the QR URI and secret
const { qrUri, secret } = await kb.auth().totp.setup()

// 2. Confirm activation with the first code from the authenticator
const { backupCodes } = await kb.auth().totp.verifySetup('123456')

// 3. Login when 2FA is enabled: signIn() does not return the sessionToken,
//    so read the response of POST /api/auth/signin directly
const res = await fetch(`${process.env.NEXT_PUBLIC_KB_URL}/auth/signin`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'x-api-key': process.env.NEXT_PUBLIC_KB_KEY! },
  body: JSON.stringify({ email, password }),
})
const data = await res.json()
if (data.requires2FA) {
  // second factor required
  const finalResult = await kb.auth().totp.verify(data.sessionToken, totpCode)
}
```

### Direct REST endpoints

```bash
# Every request carries the x-api-key: <key> header

# Sign up
POST /api/auth/signup
{ "email": "...", "password": "..." }

# Sign in
POST /api/auth/signin
{ "email": "...", "password": "..." }

# Verify OTP
POST /api/auth/otp/verify
{ "email": "...", "code": "123456" }

# Refresh token
POST /api/auth/refresh
{ "refreshToken": "<refresh_token>" }

# Current user
GET /api/auth/user
Authorization: Bearer <access_token>

# Sign-in providers (see Auth model)
GET  /api/auth/oauth/<slug>?code_challenge=<S256>&redirect_to=<url>   → { "url": "..." }
POST /api/auth/oauth/exchange       { "code": "...", "code_verifier": "..." }
POST /api/auth/oauth/<slug>/token   { "idToken": "...", "nonce": "..." }
POST /api/auth/oauth/<slug>/complete { "code": "...", "state": "...", "code_verifier": "..." }   # private flow
```


---

# SSR (Next.js)


## SSR with cookies (Next.js)

`@kronbase/ssr` stores the session in cookies instead of in memory — required so that Server Components, Server Actions and middleware can see the logged-in user. Three clients, one per context; all three share the same cookies (`access_token` / `refresh_token`).

### Server client (Server Components / Actions / Route Handlers)

**lib/kronbase/server.ts**

```typescript
import { createServerClient } from '@kronbase/ssr/server'
import { cookies } from 'next/headers'

export async function createClient() {
  const cookieStore = await cookies()
  return createServerClient(
    process.env.NEXT_PUBLIC_KB_URL!,
    process.env.NEXT_PUBLIC_KB_KEY!,
    {
      cookies: {
        getAll() { return cookieStore.getAll() },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            )
          } catch {
            // Server Component — read-only, the middleware writes the cookies.
          }
        },
      },
    }
  )
}
```

### Browser client (Client Components)

**lib/kronbase/client.ts**

```typescript
'use client'
import { createBrowserClient } from '@kronbase/ssr/client'

export function createClient() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_KB_URL!,
    process.env.NEXT_PUBLIC_KB_KEY!
  )
}
```

### Middleware (keep the session fresh on every request)

**lib/kronbase/middleware.ts**

```typescript
import { createServerClient } from '@kronbase/ssr/middleware'
import { NextResponse, type NextRequest } from 'next/server'

export async function updateSession(request: NextRequest) {
  let kbResponse = NextResponse.next({ request })

  const client = createServerClient(
    process.env.NEXT_PUBLIC_KB_URL!,
    process.env.NEXT_PUBLIC_KB_KEY!,
    {
      cookies: {
        getAll() { return request.cookies.getAll() },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
          kbResponse = NextResponse.next({ request })
          cookiesToSet.forEach(({ name, value, options }) =>
            kbResponse.cookies.set(name, value, options)
          )
        },
      },
    }
  )

  const user = await client.auth().getUser()

  if (!user && !request.nextUrl.pathname.startsWith('/auth')) {
    const url = request.nextUrl.clone()
    url.pathname = '/auth'
    return { response: NextResponse.redirect(url), user: null }
  }

  return { response: kbResponse, user }
}
```

**middleware.ts**

```typescript
import { updateSession } from './lib/kronbase/middleware'
import type { NextRequest } from 'next/server'

export async function middleware(request: NextRequest) {
  const { response } = await updateSession(request)
  return response
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}
```

### Usage

```typescript
// In a Server Component
import { createClient } from '@/lib/kronbase/server'

export default async function Page() {
  const kb = await createClient()
  const user = await kb.auth().getUser()
  // user → { id, email, role, ... } | null
}

// In a Client Component
'use client'
import { createClient } from '@/lib/kronbase/client'

const kb = createClient()
await kb.auth().signIn(email, password)   // stores the cookies by itself
await kb.auth().signOut()                  // clears them
```


---

# Database


## Database

Supabase-style query builder API on top of Oracle Autonomous Database. The client is initialized with your project's service key or API key.

### Initialize (server-side)

```typescript
import { createClient } from '@kronbase/client'

// For queries from your backend (with the service key)
const kb = createClient(
  process.env.KB_URL!,
  { serviceKey: process.env.KB_SERVICE_KEY! }
)
```

### SELECT

```typescript
// All rows
const { data } = await kb.from('PRODUCTOS').select('*').execute()

// Specific columns
const { data } = await kb
  .from('PRODUCTOS')
  .select(['ID', 'NOMBRE', 'PRECIO'])
  .execute()

// With filters
const { data } = await kb
  .from('PRODUCTOS')
  .select('*')
  .eq('ACTIVO', 1)
  .gte('PRECIO', 100)
  .like('NOMBRE', '%camisa%')
  .execute()
```

### Filter operators

```typescript
kb.from('T').select('*')
  .eq('COL', value)            // =
  .neq('COL', value)           // !=
  .gt('COL', value)            // >
  .gte('COL', value)           // >=
  .lt('COL', value)            // <
  .lte('COL', value)           // <=
  .like('COL', '%txt%')        // LIKE  (case-sensitive)
  .ilike('COL', '%txt%')       // ILIKE (case-insensitive)
  .in('COL', [1, 2, 3])        // IN (...)
  .notIn('COL', [4, 5])        // NOT IN (...)
  .isNull('COL')               // IS NULL
  .notNull('COL')              // IS NOT NULL
```

### Compound OR / AND filters

```typescript
// WHERE (CATEGORIA = 'ropa' OR CATEGORIA = 'calzado') AND STOCK > 0
const { data } = await kb
  .from('PRODUCTOS')
  .select('*')
  .orGroup(g => g
    .eq('CATEGORIA', 'ropa')
    .eq('CATEGORIA', 'calzado')
  )
  .andGroup(g => g
    .gt('STOCK', 0)
  )
  .execute()
```

### Pagination and ordering

```typescript
const { data, meta } = await kb
  .from('PEDIDOS')
  .select('*')
  .orderBy('CREATED_AT', 'desc')
  .limit(20)
  .offset(0)       // page 1
  .execute()
// meta.total → total rows without pagination
```

### Expressions in SELECT

Besides columns, `select()` accepts **computed columns**: Oracle functions, arithmetic, `CASE` and `CAST` built with the `fn`, `col`, `lit` and `cond` helpers from `@kronbase/client`. Every expression needs an output name, `.as('alias')`. The SDK does not send SQL: it sends a JSON tree in the `expressions` field and the API validates it against a closed list of functions and generates the SQL itself (literal values always travel as binds).

```typescript
import { fn, col, lit } from '@kronbase/client'

const { data } = await kb
  .from('CASO', 'c')
  .select([
    'c.ID_CASO',
    fn.nvl('a.NOMBRE', lit('Sin ambiente')).as('ambiente'),
    fn.nvl('vcm.TIPO_TAREA', lit('Sin clasificar')).as('tipo_tarea'),
    fn.trunc('c.FECHA_CREACION').as('fecha'),
    fn.upper('u.USERNAME').as('usuario'),
    col('c.FECHA_ATENCION').minus('c.FECHA_CORREO').times(24).times(60).as('minutos'),
    fn.decode('c.ESTADO',
      [[4, lit('Cerrado')], [5, lit('Cerrado')], [6, lit('Cerrado')], [7, lit('Cerrado')], [12, lit('Cerrado')]],
      'est.NOMBRE').as('estado'),
    lit(null).as('col_10'),
  ])
  .leftJoin('AMBIENTE', { left: 'c.ID_AMBIENTE', right: 'a.ID_AMBIENTE' }, 'a')
  .leftJoin('V_CLASIFICACION', { left: 'c.ID_CASO', right: 'vcm.ID_CASO' }, 'vcm')
  .innerJoin('USUARIO', { left: 'c.ID_USUARIO', right: 'u.ID_USUARIO' }, 'u')
  .leftJoin('ESTADO', { left: 'c.ESTADO', right: 'est.ID_ESTADO' }, 'est')
  .orderBy('fecha', 'desc')
  .limit(20)
  .execute()
// each row: ID_CASO, AMBIENTE, TIPO_TAREA, FECHA, USUARIO, MINUTOS, ESTADO, COL_10
```

The table names are illustrative. Expressions work with or without `joins`; with `joins`, columns are qualified as everywhere else in the query.

#### Argument rule: string = column, `lit()` = text

In every helper, an argument is interpreted like this:

| What you pass | What it is |
|---|---|
| a plain string (`'a.NOMBRE'`) | a **column** |
| `lit('Sin ambiente')` | a **text** literal |
| a number (`24`) | a numeric literal |
| `null` | the `NULL` literal |
| another expression (`fn.upper(...)`, `col(...)`) | that expression |

Text without `lit()` is taken as a column, not as text: `fn.nvl('a.NOMBRE', 'Sin ambiente')` looks for a column named `Sin ambiente` and the API rejects it (`INVALID_EXPRESSION` if it is not shaped like a column name, `UNQUALIFIED_COLUMN_WITH_JOIN` with joins, `INVALID_COLUMN` if Oracle cannot find that column). The same goes for the `cond.like` pattern: write `cond.like('c.ASUNTO', lit('%urgente%'))`. The only exceptions are the parameters that are literals by definition and are passed as plain text or numbers: the format of `toChar`/`toDate`, the unit of `round`/`trunc` on dates, the field of `extract` and the type of `cast`.

`col('x')` is the same as passing a plain `'x'`; use it to start an arithmetic chain (`col('c.A').minus('c.B')`). Arithmetic is available through `.plus()`, `.minus()`, `.times()`, `.div()` and `.concat()` (`||`). There is no unary minus: use a negative literal or `.times(-1)`.

An `Expr` without `.as()` inside `select()` throws a `TypeError` when the query is built. The SDK also throws a `TypeError` as soon as you write the expression if the alias does not match the pattern below, a number does not fit in an Oracle `NUMBER` (absolute value of `1e126` or more), a text literal is longer than 4000 characters, `lit.date`/`lit.datetime` get an invalid `Date`, `fn.coalesce` has fewer than 2 arguments, `cond.and`/`cond.or` get fewer than 2 conditions, or a `cond` helper gets an expression instead of a condition; the API still validates everything anyway. Calling `select()` again on the same builder replaces the previous columns and expressions. If every element of `select()` is an expression, the query has no plain columns; with `'*'` the result contains all columns of the main table and of each joined table, followed by the expressions.

#### Typed NULL (UNION branches)

If your application builds a `UNION` by combining the results of two queries, one branch may need a column that does not exist in the other:

```typescript
// Branch A: the column does not exist, fill it with NULL
kb.from('CASO', 'c').select(['c.ID_CASO', lit(null).as('col_10')])

// Branch B: fix the type of the empty column
kb.from('CASO', 'c').select(['c.ID_CASO', fn.cast(null, 'NUMBER').as('col_10')])
```

#### Available functions

Names are Oracle's; the SDK exposes them in camelCase (`fn.nvl`, `fn.addMonths`...). Passing a number of arguments outside the range gives `EXPRESSION_ARITY`.

| Helper | Function | Arguments |
|---|---|---|
| `fn.nvl` | `NVL` | 2 |
| `fn.nvl2` | `NVL2` | 3 |
| `fn.coalesce` | `COALESCE` | 2 to 16 |
| `fn.nullif` | `NULLIF` | 2 |
| `fn.decode` | `DECODE` | 3 to 255 (the SDK takes the `subject`, the list of pairs and an optional default) |
| `fn.greatest`, `fn.least` | `GREATEST`, `LEAST` | 1 to 16 |
| `fn.upper`, `fn.lower`, `fn.initcap`, `fn.length`, `fn.trim` | `UPPER`, `LOWER`, `INITCAP`, `LENGTH`, `TRIM` | 1 (`TRIM` only the one-argument form) |
| `fn.ltrim`, `fn.rtrim` | `LTRIM`, `RTRIM` | 1 to 2 |
| `fn.substr` | `SUBSTR` | 2 to 3 |
| `fn.instr` | `INSTR` | 2 to 4 |
| `fn.replace` | `REPLACE` | 2 to 3 |
| `fn.lpad`, `fn.rpad` | `LPAD`, `RPAD` | 2 to 3 |
| `fn.concat` | `CONCAT` | 2 |
| `fn.round`, `fn.trunc` | `ROUND`, `TRUNC` | 1 to 2; the second is an integer from -38 to 38 (decimals) or a date unit (`'MM'`, `'YYYY'`, `'DD'`, `'HH24'`, `'MI'`, `'Q'`, `'IW'`...) |
| `fn.ceil`, `fn.floor`, `fn.abs`, `fn.sign` | `CEIL`, `FLOOR`, `ABS`, `SIGN` | 1 |
| `fn.mod`, `fn.power` | `MOD`, `POWER` | 2 |
| `fn.addMonths` | `ADD_MONTHS` | 2 |
| `fn.monthsBetween` | `MONTHS_BETWEEN` | 2 |
| `fn.lastDay` | `LAST_DAY` | 1 |
| `fn.toChar` | `TO_CHAR` | 1 to 2; the second is the format (text) |
| `fn.toDate` | `TO_DATE` | 2: text and format |
| `fn.toNumber` | `TO_NUMBER` | 1 (no format) |
| `fn.extract(field, x)` | `EXTRACT(field FROM x)` | `YEAR`, `MONTH`, `DAY`, `HOUR`, `MINUTE` or `SECOND` |
| `fn.cast(x, type)` | `CAST(x AS type)` | `'NUMBER'`, `'DATE'`, `'TIMESTAMP'` or `{ varchar2: n }` (n from 1 to 4000) |
| `fn.case(...)` | `CASE` | see below |

`toChar`/`toDate` formats and `round`/`trunc` units are validated against Oracle's list of format elements (up to 64 characters); an unknown format gives `INVALID_EXPRESSION_FORMAT`. Function names are a closed list: there are no user or package functions, and no `SYS_CONTEXT`, `USER`, `LISTAGG` or analytic functions.

#### Date literals: your app sends the date

There are no helpers for `SYSDATE`, `CURRENT_DATE` or similar: your application computes the "current" date and sends it as a literal.

```typescript
// Days elapsed since creation (date - date = days)
lit.date('2026-11-09').minus('c.FECHA_CREACION').as('dias')

// A JavaScript Date uses its local components (year, month, day)
lit.date(new Date()).minus('c.FECHA_CREACION').as('dias_hasta_hoy')

// Date and time, no time zone: YYYY-MM-DDTHH:MM:SS
fn.nvl('c.FECHA_CIERRE', lit.datetime('2026-11-09T18:30:00')).as('cierre')
```

`lit.date` takes `YYYY-MM-DD` and `lit.datetime` takes `YYYY-MM-DDTHH:MM:SS` (no zone, no fractional seconds, real calendar dates); any other shape gives `INVALID_EXPRESSION`. In Oracle, `DATE ± number` adds or subtracts days and `DATE - DATE` gives days. Subtracting two `TIMESTAMP` columns does not give days but an `INTERVAL`: convert them first with `CAST(x AS DATE)`:

```typescript
fn.cast('c.FECHA_ATENCION', 'DATE').minus(fn.cast('c.FECHA_CORREO', 'DATE')).times(24).times(60).as('minutos')
```

#### CASE, DECODE and CAST

`fn.case()` creates a searched `CASE` (each `when` takes a condition from `cond`) and `fn.case(subject)` a simple `CASE` (each `when` takes a value). Close it with `.else(x)` or `.end()` (without `ELSE`, the result is `NULL` when no branch matches). Available conditions are `cond.eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like`, `isNull`, `notNull`, `in`, `and` (2 to 16 conditions), `or` and `not`; in this version conditions only exist inside a searched `CASE`.

```typescript
import { fn, lit, cond } from '@kronbase/client'

// Equivalent to the DECODE in the example above
fn.case()
  .when(cond.in('c.ESTADO', [4, 5, 6, 7, 12]), lit('Cerrado'))
  .else('est.NOMBRE')
  .as('estado')

// Simple CASE
fn.case('c.PRIORIDAD')
  .when(1, lit('Alta'))
  .when(2, lit('Media'))
  .else(lit('Baja'))
  .as('prioridad_texto')

// Several conditions and LIKE (the pattern goes through lit)
fn.case()
  .when(cond.and(cond.like('c.ASUNTO', lit('%urgente%')), cond.notNull('c.FECHA_ATENCION')), lit('Atender'))
  .end()
  .as('accion')
```

A `CASE` accepts up to 64 branches, and a `CAST` to `VARCHAR2` requires the length: `fn.cast('c.ID_CASO', { varchar2: 20 })`.

#### Ordering and grouping

You can order by an expression alias (`.orderBy('fecha', 'desc')` in the first example), also together with `limit` and `offset`. You cannot group by an expression alias: `.groupBy('fecha')` is rejected with `INVALID_GROUP_BY_COLUMN`. Group by the source columns instead:

```typescript
// Cases per status: the expression only uses columns that are in groupBy
const { data } = await kb
  .from('CASO', 'c')
  .select([fn.upper('c.ESTADO').as('estado_mayus')])
  .count('*', 'total')
  .groupBy('c.ESTADO')
  .execute()
```

When the query has `groupBy`, aggregates or `having`, every column used inside an expression must be in `groupBy` (otherwise `EXPRESSION_NOT_GROUPED`). With aggregates and an expression that uses columns but no `groupBy`, the error is `GROUP_BY_REQUIRED`. An expression made only of literals (`lit('x').as('origen')`) is always valid next to aggregates. Aggregates inside expressions (`ROUND(AVG(x), 2)`) are not supported yet, nor are expressions inside aggregates, filters, `orderBy` or `groupBy`. Finally, `select('*')` (or `'Q.*'`) combined with expressions and also with aggregates or `groupBy` is rejected with `STAR_WITH_AGGREGATES`: list the columns.

#### Output column names

The row key of each computed column is the alias in UPPERCASE (`.as('ambiente')` returns `AMBIENTE`), then `columnCase` is applied as with any other column: with `'lower'` the key is `ambiente`; with `'camel'`, `.as('tipoTarea')` is emitted as `TIPO_TAREA` and the row has `tipoTarea`. Output order is: `select` columns, expressions, then aggregates.

The alias must match `^[A-Za-z_][A-Za-z0-9_]*$` and be at most 128 characters **after** normalizing it with `columnCase` (`'camel'` adds underscores). It cannot repeat across expressions, nor match an `as` label of the `select`, the name of a listed column or an aggregate alias (`INVALID_ALIAS`). With `'*'` the API does not know the table's columns: if the alias matches one of them, the row carries a duplicated key and the value the driver resolves wins, so pick distinct aliases.

#### Limits

| Limit | Value |
|---|---|
| Expressions per query | 50 |
| Nesting depth | 10 levels |
| Nodes per expression | 128 |
| Nodes per query | 1000 |
| Text of a literal | 4000 bytes (65536 across all literals in the query) |
| Alias | 128 characters after normalization |
| `CASE` branches | 64 |
| `cond.in` values | 100 |

Limits are not configurable. A node is each function, column, literal, operator, `CAST`, `EXTRACT` or `CASE` branch.

#### SELECT only

Expressions only exist in `SELECT` operations. The SDK always sends `operation: 'SELECT'`; if you build the request by hand over HTTP, `operation` must be exactly `SELECT` in uppercase, and `expressions` with any other operation is rejected with `EXPRESSIONS_SELECT_ONLY`.

#### Errors

Validation errors come back as `403` with `{ success: false, error, code }` (like the other query rules); `error` points to the path of the problem (`expressions[2].expr.args[1]`) without repeating the value you sent.

Over HTTP (`/query` and `/transaction`), more than 50 expressions, an `expressions` that is not an array, or an item that is not an object is rejected earlier by the JSON schema with `400` and code `FST_ERR_VALIDATION`; `TOO_MANY_EXPRESSIONS` (`403`) only comes through realtime or the dashboard proxy.

| Code | When it appears |
|---|---|
| `INVALID_EXPRESSION` | invalid shape: unknown node type, unknown key, wrong type, malformed literal (date, out-of-range number), an argument that had to be a literal, `CASE` with the wrong kind of `when`, missing or extra `CAST` `length` |
| `EXPRESSION_FUNCTION_NOT_ALLOWED` | function not in the list (`SYSDATE`, `USER`, `LISTAGG`...) |
| `EXPRESSION_ARITY` | number of arguments out of range (`NVL expects 2 arguments, got 3`) |
| `INVALID_EXPRESSION_FORMAT` | format or date unit not in the list, or precision outside -38 to 38 |
| `EXPRESSION_TOO_DEEP` | more than 10 nesting levels |
| `EXPRESSION_TOO_LARGE` | too many nodes or literals too long |
| `TOO_MANY_EXPRESSIONS` | more than 50 expressions |
| `EXPRESSIONS_SELECT_ONLY` | `expressions` in a non-`SELECT` operation |
| `EXPRESSIONS_DISABLED` | the operator turned expressions off on that server (see below) |
| `EXPRESSION_NOT_GROUPED` | a column of an expression is not in `groupBy` |
| `STAR_WITH_AGGREGATES` | `'*'` together with expressions and aggregates or `groupBy` |
| `INVALID_ALIAS` | invalid or repeated alias, alias clashing with another output column, or too long |
| `INVALID_NAME`, `INVALID_COLUMN_QUALIFIER`, `UNQUALIFIED_COLUMN_WITH_JOIN`, `INVALID_GROUP_BY_COLUMN`, `GROUP_BY_REQUIRED` | the same rules as for `select` columns, applied to the columns of expressions |

Errors detected by Oracle at execution time come back as `400` with a generic message:

| Code | Cause |
|---|---|
| `EXPRESSION_TYPE_MISMATCH` | incompatible types (ORA-00932, ORA-00975), for example a `CASE` with branches of different types |
| `INVALID_NUMBER` | a value is not a number (ORA-01722), for example `TO_NUMBER` of a text |
| `INVALID_DATE_CONVERSION` | a value is not a date for the given format (ORA-01830, 01839, 01840, 01841, 01843, 01847, 01858, 01861) |
| `DIVISION_BY_ZERO` | division by zero (ORA-01476) |
| `EXPRESSION_NOT_GROUPED` | column outside `GROUP BY` detected by Oracle (ORA-00979) |
| `RESULT_TOO_LONG` | a concatenation exceeds the maximum length (ORA-01489) |

These Oracle errors are now returned as `400` with their code for every query and operation, not only with expressions; they used to arrive as `500` with `DB_ERROR`. If your application compared against `DB_ERROR` for these cases, update the check. A column that does not exist, for example a name such as `SYSDATE` used as a column, gives `400` with `INVALID_COLUMN`.

#### Compatibility with older servers

An older API would silently ignore `expressions` and return different columns than requested. So, before sending a query, transaction or subscription with expressions, the SDK calls `GET /api/capabilities` (no API key; it returns `{ success: true, data: { features: ['select-expressions'] } }`) and caches the result per URL. If the server does not support expressions, it fails with the `EXPRESSIONS_UNSUPPORTED` code without sending the query: `execute()` and `subscribe().connect()` reject with an `Error` that has `code`, and `transaction()` returns `{ success: false, code: 'EXPRESSIONS_UNSUPPORTED', failedAt }`. The SDK also checks that the response to a `SELECT` with expressions includes `meta.expressions`; if it does not, it also reports `EXPRESSIONS_UNSUPPORTED`: `execute()` rejects, `transaction()` returns `{ success: false, code: 'EXPRESSIONS_UNSUPPORTED', failedAt, results }` with the index of that `SELECT` (the rest of the transaction was already committed; the `SELECT` changed nothing), and a subscription emits the error on its first result and is cancelled. To recognize this case, compare with the `EXPRESSIONS_UNSUPPORTED_CODE` constant or use `isExpressionsUnsupported(errorOrResult)`, both exported by `@kronbase/client`. On a self-hosted or BYOC deployment, update the instance (the dashboard's **Update** button) or remove the expressions. Queries without expressions skip this check.

If you run a self-hosted or BYOC instance and need to turn expressions off, set `QUERY_EXPRESSIONS_ENABLED=false` in the API container's environment and restart the container. Only the value `false` turns them off (any other value, or leaving it unset, keeps them on). While off, `/api/capabilities` stops advertising them and queries with expressions are rejected with `EXPRESSIONS_DISABLED`.

#### Transactions and realtime

Expressions work in the `SELECT` operations of `kb.transaction()` (also with `.forUpdate()`) and in realtime subscriptions; see the transactions and realtime sections.

### INSERT

```typescript
const { data } = await kb
  .from('CLIENTES')
  .insert({
    NOMBRE: 'Ana García',
    EMAIL: 'ana@ejemplo.com',
    ACTIVO: 1,
  })
  .execute()
// data[0] → inserted row
```

### UPDATE

```typescript
const { data } = await kb
  .from('CLIENTES')
  .update({ ACTIVO: 0 })
  .eq('ID', 42)
  .execute()
```

### DELETE

```typescript
await kb
  .from('SESIONES')
  .delete()
  .lt('EXPIRES_AT', new Date().toISOString())
  .execute()
```

### Transactions

Several atomic operations — if one fails, all of them roll back.

```typescript
const result = await kb.transaction([
  kb.from('PEDIDOS')
    .insert({ CLIENTE_ID: 1, TOTAL: 350 })
    .build(),
  kb.from('INVENTARIO')
    .update({ STOCK: inventario.STOCK - cantidad })
    .eq('PRODUCTO_ID', productoId)
    .build(),
])

if (!result.success) {
  console.error('Rollback at operation', result.failedAt, result.error)
}
```

### Parent and children in one transaction: returning() and ref()

To insert a record and use the ID Oracle generates for it in child rows, within the same transaction, use `returning()` on the parent operation and `ref(op, 'COLUMN')` on the children. `op` is the position (starting at 0) of the operation that returned the value.

```typescript
import { ref } from '@kronbase/client'

const result = await kb.transaction([
  kb.from('PLANES').insert({ NOMBRE: 'Plan semanal' }).returning(['ID']).build(),
  kb.from('PLAN_ITEMS')
    .insertMany(items.map((i) => ({ ...i, PLAN_ID: ref(0, 'ID') })))
    .build(),
])
```

> **Note:** `ref()` works in `data`, in the rows of `insertMany` and in filter values. It can only point to a previous INSERT operation in the same transaction and to a column included in its `returning()`; otherwise it returns `INVALID_REF` without executing anything. `returning()` supports NUMBER, VARCHAR2 (e.g. UUID), RAW (as hex) and DATE columns.

### insertMany()

Inserts 1 to 1000 rows in a single operation. All rows must have the same columns, and it can't be combined with `data` or `returning()`. A transaction allows up to 100 operations.

### upsert()

```typescript
await kb.from('PERFILES')
  .upsert(
    { USER_ID: 'u1', NOMBRE: 'Ana' },        // or an array of rows (1 to 1000)
    { onConflict: ['USER_ID'], ignoreDuplicates: false }
  )
  .execute()
```

It runs as a `MERGE`: it updates the row if one with the same `onConflict` already exists, or inserts it. With `ignoreDuplicates: true` existing rows are left untouched. It works inside `transaction()` and with `ref()`, but doesn't support `returning()`.

> **Note:** With RLS enabled, the `MERGE` only sees the rows visible to the user: if two users upsert with the same key, each gets their own row, unless uniqueness is global (a unique index that doesn't include the user).

> **Important:** Oracle only allows the `MERGE` on tables without RLS or with **owner column** RLS. On a table with a custom rule, group membership or per-operation rules, `upsert()` responds `400` with the code `RLS_UPSERT_UNSUPPORTED` and changes no rows: use `insert()` and `update()` separately.

### Procedures inside a transaction

For logic with conditions or loops, create your own PROCEDURE or FUNCTION (`CREATE OR REPLACE PROCEDURE` is allowed in the dashboard's SQL runner and in `kronbase migration`) and invoke it with `plsql` inside `transaction()`. Only already-created procedures can be invoked, not anonymous blocks. RLS policies apply the same way inside the procedure.

### Row-level security (RLS)

RLS makes each user see and modify only the rows of a table that match a rule. It is enabled per table from the project's **Seguridad** (Security) tab in the dashboard (Cloud and dedicated deployments) or with `kronbase rls apply` (see CLI). The rule is a SQL condition that uses `current_user_id()`, the id of the token's user, for example `OWNER_ID = current_user_id()`; the server picks the mechanism:

- **Owner column** (`COLUMN = current_user_id()`): the column is also filled in with the user's id on insert.
- **Group membership** (the rule queries the same table it protects): you must give the group column and the user column. The written rule only selects this mode; what is applied is `GROUP IN (SELECT GROUP FROM TABLE WHERE USER = current_user_id())` with the two given columns.
- **Custom rule** (any other condition): filters reads, updates and deletes; inserts are not filtered.

#### Permission-based rules: `current_user_has_permission()`

A rule can also ask whether the token's user has an RBAC permission (see "Permissions (RBAC)" in [Authentication model](/en/docs#auth-model)), for example so that whoever has `tickets.view_all` sees every ticket and everyone else only their own:

```sql
current_user_has_permission('tickets.view_all') OR OWNER_ID = current_user_id()
```

- It uses the same rule as `getPermissions()`: permissions from the user's roles plus those granted directly, minus those denied directly (a denial beats a role). The code is compared exactly, case-sensitively.
- It is evaluated on every query: granting or removing a permission or a role takes effect on the next request, without waiting for a session or a cache to expire.
- It does not check whether the user is active (same as `current_user_id()`): a deactivated user keeps what their permissions let them see while their token is still valid. To cut access immediately, remove the permission or the role.
- The argument must be a literal code in single quotes (letters, digits, `_`, `.`, `:` and `-`, up to 100 characters). A column, a variable, a concatenation or any other expression is rejected with `400`. A code containing `--` is rejected too, because rules do not allow SQL comments.
- If the code does not exist in `AUTH_PERMISSIONS`, nobody has it: the condition is false (no error). Check that the code is spelled right.
- `current_user_has_permission('…')` on its own is a valid rule (only users with the permission see rows). Combined with other conditions it creates a custom rule: inserts are not filtered.
- It works the same in `kronbase rls apply`, in `kronbase rls sync` and in the **Seguridad** (Security) tab.
- The server stores the expanded rule: the **Seguridad** (Security) tab, `GET` and `kronbase rls list` show the equivalent SQL query (about 700 characters per call), not what you wrote. The 4000-character limit also applies to the expanded rule, so about 5 calls fit in one rule; beyond that it is rejected with `400`.
- The permission lookups use the indexes of the `AUTH_*` tables and do not depend on the size of the protected table.
- It only works when the rule is sent without `mode` (as the dashboard and the CLI do) or in [per-operation rules](#per-operation-rules-using-with-check); with an explicit `mode: "PREDICATE"` it is rejected with `400`.

It cannot be enabled on Kronbase's own tables (`AUTH_…`), and a table has a single policy: to change it without disabling it, use `kronbase rls sync` (see below). Disabling it makes every row visible again to any request with access to the table. The `service_role` key is not filtered by RLS, and neither are the requests of a user with the `rls.bypass` mark (meant for background processes; see "Service users: the `rls.bypass` mark" in [Auth model](/en/docs#auth-model)). Requests without a user (the `anon` key without a token, including public tables and realtime without a session) stop seeing rows of a table with RLS.

### Per-operation rules (USING / WITH CHECK)

When a single rule is not enough, a table can have a different rule for each operation, in the style of Postgres policies:

- `select.using`: which rows the user can read.
- `insert.withCheck`: what a new row must look like to be accepted.
- `update.using`: which rows the user can update; `update.withCheck` (optional): what the row must look like after the change. Without `withCheck`, the updated row must still satisfy `using`.
- `delete.using`: which rows the user can delete.

> **Important:** An operation you do not declare is **denied** to every user except `service_role` (an INSERT responds 403 `RLS_VIOLATION`; an UPDATE or DELETE affects no rows). There are no "ungoverned" operations: if an operation should be open, declare it with the condition that applies. UPDATE and DELETE also only reach rows the user can read with `select`: without `select`, nothing can be updated or deleted either.

Separation-of-duties example: each employee requests overtime for themselves; approvers (table `APPROVERS`) see other people's requests and approve them, but never their own.

```json
{
  "tables": {
    "OVERTIME_REQUESTS": {
      "select": { "using": "REQUESTER_ID = current_user_id() OR (REQUESTER_ID <> current_user_id() AND EXISTS (SELECT 1 FROM APPROVERS a WHERE a.USER_ID = current_user_id()))" },
      "insert": { "withCheck": "REQUESTER_ID = current_user_id() AND APPROVED_BY IS NULL AND STATUS = 'PENDING'" },
      "update": {
        "using": "REQUESTER_ID <> current_user_id() AND STATUS = 'PENDING' AND EXISTS (SELECT 1 FROM APPROVERS a WHERE a.USER_ID = current_user_id())",
        "withCheck": "REQUESTER_ID <> current_user_id() AND (APPROVED_BY IS NULL OR APPROVED_BY = current_user_id()) AND (STATUS <> 'APPROVED' OR APPROVED_BY = current_user_id())"
      },
      "delete": { "using": "REQUESTER_ID = current_user_id() AND STATUS = 'PENDING'" }
    }
  }
}
```

With these rules: nobody can create a request on someone else's behalf or already approved (403 `RLS_VIOLATION`); an approver who tries to approve their own request updates no rows; approving someone else's request with a third person as approver, marking it approved without signing it (empty `APPROVED_BY`) or taking over the request responds 403 `RLS_VIOLATION`; requesters can only delete their pending requests.

Apply them with `kronbase rls sync` (this same format in `rls.json`), with `kronbase rls apply <table> --select "..." --insert "..." --update "..." --update-check "..." --delete "..."` or through the API. Each table uses **either** `predicate` **or** per-operation rules, never both. The dashboard lists them and can disable them, but they are created from the CLI or the API.

Details:

- Each condition follows the same rules as `predicate`: it must use `current_user_id()` (it can also use `current_user_has_permission()`, see "Permission-based rules" above), at most 4000 characters once expanded, no `;`, comments or system packages, and it cannot query the same table it protects (for group membership use `predicate` with `groupColumn` and `userColumn`). It can query other tables of the project.
- `update` and `delete` only reach rows the user can also read: Kronbase combines their `using` with `select.using` (both must hold), and without `select` they affect no rows. That way a `using` wider than `select` cannot be used to find out, from the number of affected rows, which rows exist without being able to see them. `update.withCheck` does not include `select`: the updated row may end up outside what the user sees. `insert` does not depend on `select`.
- `insert.withCheck` is evaluated against the row being inserted; to check other rows, use a subquery (for example `EXISTS (SELECT 1 FROM ...)`).
- **`update.withCheck` limitation:** in Oracle, `withCheck` is also required of the row **before** the change. A row can only be updated if it satisfies `using` and `withCheck` before the change, and the result must satisfy `withCheck`. Write it so that both the original and the final row satisfy it, as in the example (`APPROVED_BY IS NULL OR APPROVED_BY = current_user_id()`).
- Changing the rules of a table that already has per-operation rules never leaves it open or closed: the change is immediate. Switching between `predicate` and per-operation rules is a mode change (see the warning below).
- The `service_role` key is not filtered, and requests without a user neither see nor modify rows, as in the other modes.
- `upsert()` is not available on these tables (`400 RLS_UPSERT_UNSUPPORTED`, see [upsert()](#upsert)).
- On the local stack (`kronbase start`), update the dashboard image together with the API image: a dashboard from an earlier version does not list tables with per-operation rules.

### Sync from a file

`kronbase rls sync` reads `kronbase/rls.json` (or the `--file` path) and leaves the project's policies as the file says. Use it to keep the rules versioned next to your code and to change them without disabling RLS:

```json
{
  "tables": {
    "TASKS": { "predicate": "OWNER_ID = current_user_id()" },
    "NOTES": { "predicate": "USER_ID = current_user_id()" },
    "HOUSEHOLD_MEMBERS": {
      "predicate": "HOUSEHOLD_ID IN (SELECT HOUSEHOLD_ID FROM HOUSEHOLD_MEMBERS WHERE USER_ID = current_user_id())",
      "groupColumn": "HOUSEHOLD_ID",
      "userColumn": "USER_ID"
    }
  }
}
```

Each entry accepts `predicate` (at most 4000 characters), `groupColumn` and `userColumn` (only for group membership, as in `rls apply`), or per-operation rules instead (`select`, `insert`, `update`, `delete`; see above). Keys are just the table name (no schema, no quotes), are case-insensitive and cannot be repeated. Per table, the result is:

- `created`: the table had no policy and one is created.
- `updated`: the policy exists and differs from the file. Changing the rule within the same mode never leaves the table open; changing the mode temporarily denies non-bypass users (see the warning).
- `unchanged`: it already matches the file.
- `removed`: only with `--prune`, for tables that have a policy but are not in the file.

`--prune` is opt-in: without it, tables missing from the file are left alone. With `--prune` the file must declare at least one table (an empty `tables` is refused so it cannot remove RLS from the whole project) and, if any key is not a valid table name, the whole batch is refused without applying anything. A batch accepts up to 200 tables.

Only one sync runs at a time per project: if another one arrives while one is in progress, it is refused with a 409 error without applying anything; run it again in a few seconds. `--dry-run` and `--check` write nothing, so they are never refused for this.

`--dry-run` and `--check` write nothing: they validate that the tables and columns exist and that the rule is valid, but they do not grant access to tables the rule references nor try the owner column's default, so they cannot catch every failure at apply time (for example, a `DEFAULT` on the owner column that the database rejects). With `--prune`, the simulation reports `removed` without validating. Each table is processed on its own: if one fails it is reported as `error` and the rest are applied.

> **Warning:** Changing a table's **mode** (for example, from owner column to custom rule) denies rows to users other than `service_role` for a brief moment while it swaps. Changing only the rule within the same mode does not have that effect. If a mode change fails midway, the table stays closed (rows denied to non-bypass users, never exposed) until a retry or a new `rls sync` succeeds; re-running `sync` repairs it.

### DBMS_SCHEDULER jobs and processes without a user

RLS policies deny rows to every session that doesn't come from the API with a user or with `service_role`. That includes any background job-queue session (`DBMS_SCHEDULER`, `DBMS_JOB` and similar) and the procedures they run: they run inside the database without going through the API, so on a table with RLS they see 0 rows, even when they run as the project's schema user.

If your jobs need to read or change those tables (for example, sending pending emails or closing records every night), turn on **scheduler-bypass** for the project:

```bash
kronbase rls scheduler-bypass on -t prod      # turn on
kronbase rls scheduler-bypass status -t prod  # show the current state
kronbase rls scheduler-bypass off -t prod     # back to the default behavior
```

**Requirement:** the project's schema user must be able to create jobs (the `CREATE JOB` privilege). Kronbase does not grant it: you grant it where you manage the database (dedicated deployment or local stack). On Kronbase Cloud, project users don't have `CREATE JOB` today, so the flag has no effect there.

With scheduler-bypass on, and only while the project is active (suspended or deleted counts as off), the policies show every row only to a session that meets all three conditions:

- it is a background job-queue session of the database (`DBMS_SCHEDULER`, `DBMS_JOB` and similar; Oracle reports it in `SYS_CONTEXT('USERENV', 'BG_JOB_ID')`, which the client cannot set);
- it runs as the project's schema user (the owner of the tables). A job owned by another user that reads those tables still sees 0 rows;
- it did not go through the API.

Everything else is unchanged: a direct connection as the schema user (SQL Developer, SQL*Plus, your own app) still sees 0 rows, even if it sets `MODULE`, `ACTION` or `CLIENT_IDENTIFIER` to look like a job; so does `DBMS_SCHEDULER.RUN_JOB` with `use_current_session => TRUE`, which runs in your session. API requests (users, `anon`, `service_role`) are filtered exactly as before, and one project's flag doesn't affect any other project. Off (the default), the behavior is the same as always.

> **Security notice:** with scheduler-bypass on, you trust every background job-queue session that runs as the schema user. Anyone with that user's credentials (or the `CREATE ANY JOB` privilege) can create a job that sees every row. Turn it on only if those credentials are protected as carefully as the `service_role` key, and turn it off when you no longer need it. If reading the setting fails, the policies deny rows (they never expose them).

### RLS errors

If an operation leaves a row outside the user's scope (for example, an UPDATE that changes an ownership column to a value the user has no access to), the API responds with 403 and the code `RLS_VIOLATION`. Inside a transaction it arrives as `result.code` and everything is rolled back. If you need to move a row between groups, use DELETE + INSERT in a transaction.

An `upsert()` on a table whose policy Oracle does not allow in a `MERGE` responds 400 with the code `RLS_UPSERT_UNSUPPORTED` (see [upsert()](#upsert)).

### External data sources

Besides its own database, a project can query an external Oracle database (another cloud, an ERP, your own server) by registering it as a source. It is **read-only**: `SELECT` only, no PL/SQL, writes or transactions. It is server-to-server communication, so it only works with the `service_role` key. Only Oracle is supported today.

#### Add a source from the dashboard

In the project, **External sources** section > **Add source**. The fields are name, host, port (1521 by default), service name, user and password. The name is what you use in code: lowercase letters, digits, `_` or `-`, starting with a letter, up to 40 characters.

- **Test connection** checks host, port, service and credentials before you use the source. Once created, the **Tables** button lists the tables visible to the external user and their columns.
- **Encrypted connection (TLS)** is on by default.
- Use a **read-only** database user with access only to the tables you want to expose.
- The password is write-only: it is stored encrypted and no response or screen ever shows it again. When editing, leave it empty to keep it.
- If the source ends up in the **Needs password** state (`needs_password`, for example after the deployment's encryption key changed), queries return `SOURCE_NEEDS_PASSWORD` until you edit the source and enter the password again.

#### Querying a source

```typescript
const { data } = await kb   // client with the service key
  .source('erp')
  .from('CLIENTES')
  .select(['ID', 'NOMBRE'])
  .eq('ACTIVO', 1)
  .limit(10)
  .execute()
```

`client.source(name)` only offers `from(...).select(...)` and the filters, ordering, pagination, aggregates (`count`, `sum`, `groupBy`...) and `JOIN`s between tables of the same source; it has no `insert`, `update`, `delete` or procedures. Over HTTP it is `POST /api/query` with the `source` field in the body, next to `table`, `operation: 'SELECT'` and the usual fields; the response has the same shape as a normal query.

The project's RLS and the `AUTH_*` table restrictions do not apply to the external database: you see whatever the external user can see. Tables of the project's database cannot be joined with a source's tables, nor can tables from different sources. The same default and maximum row limits as a normal query apply.

#### Network

- **Kronbase Cloud:** the host must resolve only to public IP addresses; private, loopback and link-local addresses are rejected. The check is not done only when the source is registered: it is repeated every time the source's connection pool is opened. When opening it, Kronbase resolves the host, validates the IP and connects to that IP for as long as the pool stays open; the pool is recreated (and the address checked again) after a period of inactivity or when the source's connection settings are edited, so a DNS change for the host takes effect from then on. Your database must be reachable from the Internet (with your firewall open accordingly).
- **Dedicated (BYOC) deployment:** hosts on private networks can also be used, as long as they are reachable from the API server.

#### Limits

- There is a per-project limit on sources; once reached, creating another is rejected.
- The connection and each query have a maximum time. Each source has only a few simultaneous connections, a project keeps only a few sources connected at once, and the server has an overall cap: with no free connection you get `SOURCE_BUSY`, and a slow source answers `SOURCE_TIMEOUT`, instead of blocking everything else.
- `source` cannot be used inside `/api/transaction`.

#### Errors

| Code | HTTP | Meaning and what to do |
|---|---|---|
| `SOURCE_REQUIRES_SERVICE_ROLE` | 403 | Only the `service_role` key can use `source`; do it from your server. |
| `EXTERNAL_READONLY` | 403 | The operation is not `SELECT`; external sources are read-only. |
| `SOURCE_NOT_FOUND` | 404 | No source with that name exists in the project; check the name. |
| `SOURCE_NEEDS_PASSWORD` | 409 | The source needs you to re-enter the password in the dashboard. |
| `SOURCE_UNREACHABLE` | 502 | Could not connect (host, port, service, credentials, TLS or network). Use **Test connection**. |
| `SOURCE_QUERY_FAILED` | 502 | The external database rejected the query (missing table or column, insufficient privileges). Check the query and the external user's privileges. |
| `SOURCE_BUSY` | 503 | No free connection right now: the source, the project's limit or the server is at its cap. The response carries `Retry-After`. Retry. |
| `SOURCE_TIMEOUT` | 504 | The query exceeded the time limit; narrow it with filters or `limit`. |
| `SOURCE_NOT_SUPPORTED_IN_TRANSACTION` | 400 | `source` is not accepted in `/api/transaction`. |

Error messages do not include details from the external database.

#### Limitations

- The TLS connection verifies the server certificate. In this first version the verification is strict: a certificate that is not valid for the IP address Kronbase connects to (for example one that only declares a DNS name) can be rejected, and the source then reports a connection error (`SOURCE_UNREACHABLE`).
- Wallet and mTLS (for example Oracle Autonomous with mandatory mTLS) are not supported yet.
- Oracle only for now.
- No writes, transactions or realtime.
- `JOIN` only between tables of the same source: not with the project's database nor across different sources.

### Column names

```typescript
// By default Oracle returns UPPERCASE
// You can convert with columnCase:
const { data } = await kb
  .from('USUARIOS')
  .select('*')
  .columnCase('camel')   // 'original' | 'lower' | 'camel'
  .execute()
// ID_USUARIO → idUsuario
```


---

# Storage


## Storage (Buckets)

File storage on top of OCI Object Storage with the SDK's chainable API. Buckets are created and managed from the dashboard (Buckets tab).

### Initialize the client

```typescript
import { createClient } from '@kronbase/client'

const kb = createClient(
  process.env.KB_URL!,
  { serviceKey: process.env.KB_SERVICE_KEY! }
)
```

### Upload a file

```typescript
// upload(path, data) — data can be a Buffer, Blob, File or ArrayBuffer
const result = await kb
  .bucket('my-bucket')
  .upload('invoices/january.pdf', fileBuffer)
  .contentType('application/pdf')
  .metadata({ customer: 'company-abc' })   // optional
  .execute()

// result.data.path       → file path
// result.data.size       → size in bytes
// result.data.etag       → object ETag
// result.data.uploadedAt → timestamp
```

### Download a file

```typescript
// As an ArrayBuffer
const buffer = await kb
  .bucket('my-bucket')
  .download('invoices/january.pdf')
  .arrayBuffer()

// As a Blob
const blob = await kb
  .bucket('my-bucket')
  .download('invoices/january.pdf')
  .blob()
```

### Signed URL (direct temporary access)

```typescript
const result = await kb
  .bucket('my-bucket')
  .signedUrl('invoices/january.pdf', {
    expiresIn: 3600,      // seconds (default 1 hour)
    operation: 'GET',     // 'GET' | 'PUT'
  })
  .execute()

// result.data.url       → temporary URL for direct download
// result.data.expiresAt → when it expires
```

### Delete a file

```typescript
const result = await kb
  .bucket('my-bucket')
  .delete('invoices/january.pdf')
  .execute()

// result.data.deletedAt → deletion timestamp
```

> **Note:** The bucket name in the SDK is a bucket of your project. The key determines the project, and each request only sees files under that project's prefix: files from other projects are inaccessible. With a `service_role` key (as in the examples above) you write and delete in any bucket; with an `anon` key and a user's session, only what the bucket policy allows (see "Uploading and deleting with the user session").

### Accepted file names

A file's path inside the bucket (for example `invoices/2024/año (1).pdf`) is validated the same way in the SDK, the dashboard and the CLI:

- Folders are separated with `/`. Each part can contain letters and digits from any language (accents, `ñ`, Chinese, etc.), spaces and these signs: `_ . - ( ) [ ] + , @ = & '`.
- `\ % ? * : " < > | #`, control characters, spaces other than the regular space (for example the no-break space) and invisible or ignorable characters are not accepted: text direction marks, zero-width spaces and joiners, variation selectors (such as the one that turns a symbol into an emoji), the combining grapheme joiner U+034F and the Korean filler characters (U+115F, U+3164, U+FFA0).
- A part cannot start with a lone combining accent or mark, have one right after a dot, or consist only of dots and marks; marks do not count for the space rules either (a space followed by a combining accent right before the dot is rejected just like `report .pdf`).
- Empty parts (`//`, `/` at the start or end), `.` and `..` are not accepted, nor spaces at the start or end of a part, or right before a dot (`report .pdf`). Exception for compatibility: the SDK (`kb.bucket(...)`) still removes leading `/`, collapses `//` into a single `/` and trims spaces at both ends before validating (`/foo.png` is stored as `foo.png`); the dashboard and the CLI reject them.
- The path is normalized to Unicode NFC: a name written with combining accents (as macOS provides them) is stored the same as its composed form, and the upload response returns the path as stored.
- Maximum length: 1024 bytes in UTF-8, counting the project and bucket names (`<project>/<bucket>/<path>`). An accented character takes 2 bytes and a Chinese one, 3.

### Upload limits

- Maximum size per file: 100 MB by default (depends on the installation).
- To protect Kronbase Cloud there is a cap on bytes being uploaded at once. It only kicks in when the server is busy: then it shares the room between clients (all projects of the same owner count together). The dashboard and the CLI also have a maximum number of simultaneous uploads per client. Normal usage (several parallel uploads of tens of MB, or one file up to the maximum) is not affected. When there is no room, the upload answers `429` with the code `UPLOADS_BUSY` and a `Retry-After` header (seconds): try again after that time. The CLI does it on its own.
- An upload is cut off if the client stops sending data for 30 s, or if it takes longer than it would at a minimum speed of 128 KB/s (at least 120 s, and at most the time for the maximum file size: about 13 minutes for 100 MB, even if the client declares a larger size). The deadline is computed from the size the request declares (`Content-Length`); if it does not declare one (chunked transfer), the fixed 120 s minimum applies. In that case the server answers `408` with the code `UPLOAD_TIMEOUT` and closes the connection; depending on the HTTP client, it may show up as a dropped connection instead of a `408`. The CLI retries it.
- If the storage does not answer within 45 s, the upload answers `504` with the code `STORAGE_TIMEOUT`; try again. If the connection stays idle for too long, it may also show up as a dropped connection.
- After a `504`, the upload keeps running in the background until the storage answers or its own deadline runs out (120 s by default); meanwhile, a request to delete that bucket may answer `409` (`UPLOADS_IN_PROGRESS`): try again after that time.
- Note: after a `504`, the first upload may still finish saving in the background. If the same path is retried meanwhile, the used quota may be overcounted by up to that file's size (only one file is stored).
- When a bucket deletion is requested, new uploads to that bucket answer `409` (`BUCKET_DELETING`) and the deletion waits a few seconds for the uploads already in progress to finish. If they do not finish in time, it answers `409` (`UPLOADS_IN_PROGRESS`) and the bucket accepts uploads again: try again.

### Importing existing files

To load files you already have into a bucket (for example, when migrating from another storage), use the CLI's `kronbase storage import`: it uploads a local folder keeping its subfolders, skips what is already uploaded and ends with a report. See the "CLI" section.

### Uploading and deleting with the user session

By default, uploading and deleting files requires a `service_role` key, so the file would have to go through your server. If you want the browser or mobile app to upload and delete directly with the user's session, define a **policy** on the bucket. Without a policy nothing changes: a request with the `anon` key and a user's token gets `403` (`FORBIDDEN`). The `anon` key without a token can never write.

Each bucket accepts at most one policy per operation (`upload`, `delete` and `read`), with two settings:

- **Scope:** `own-folder` (only under the user's folder, `<user id>/…`) or `bucket` (any path in the bucket).
- **Permission** (optional): the code of an RBAC permission (see "Permissions (RBAC)" in the authentication model) that the user must have. It is evaluated on the server with the user's roles and permissions; it is not inside the token.

Valid combinations:

| Scope | Permission | Who can |
|---|---|---|
| `own-folder` | none | Any user with a session in the project, only under `<their id>/…` |
| `own-folder` | `storage.write` | Users with that permission, only under `<their id>/…` |
| `bucket` | `storage.write` | Users with that permission, on any path in the bucket |
| `bucket` | none | Does not exist: rejected when saving the policy |

The user's folder is always the token's `sub`, that is, their user id. Policies are managed from the dashboard (bucket, "Acceso con el token del usuario" section) or with `kronbase storage policy` (see the "CLI" section).

```typescript
// Browser: createBrowserClient(url, anonKey), with the anon key (never service_role)
import { createBrowserClient } from '@kronbase/ssr/client'

const kb = createBrowserClient(process.env.NEXT_PUBLIC_KB_URL!, process.env.NEXT_PUBLIC_KB_KEY!)

// getUser() renews the session if the access token expired; bucket() does not renew it
const user = await kb.auth().getUser()
if (!user) throw new Error('Sign in first')

await kb.bucket('avatars')
  .upload(`${user.id}/avatar.png`, file)       // the folder is the user id
  .contentType('image/png')
  .execute()

await kb.bucket('avatars').delete(`${user.id}/avatar.png`).execute()
```

This example requires an `upload` and a `delete` policy on `avatars` with `own-folder` scope. A user who tries to write outside their folder gets `403` with `STORAGE_POLICY_DENIED`.

Things worth knowing:

- **No policy, no token access.** An operation without a policy responds as before (`403` `FORBIDDEN`). Having a policy for `upload` does not open `delete`, or the other way around. Other errors can arrive before that `403`: a bucket that does not exist (`404`) or an invalid path (`400`) are answered first, so those responses do not tell you whether a policy exists.
- **With `serviceKey` the token is ignored.** If the client is created with a `service_role` key, the request goes as `service_role`: no policy applies and the user is not recorded. Use `serviceKey` only on your server.
- **Overwriting.** Uploading to an existing path overwrites it. With `own-folder` the user can only overwrite their own files; with `bucket`, anyone with the permission can overwrite and delete any file in the bucket, which is exactly what that policy means.
- **Quota.** When overwriting, only the size difference is charged, and deleting frees the file's space. This holds with any key, `service_role` included. Deleting a file that does not exist responds `200`.
- **Per-user limit.** Each user can have at most 2 simultaneous uploads; the third gets `429` with `UPLOADS_BUSY` and `Retry-After`. On a self-hosted install it is changed with `UPLOAD_MAX_PER_USER`.
- **Audit.** Each upload or delete with a token that succeeds is recorded in your project's `AUTH_AUDIT_LOG` table (actions `storage.upload` and `storage.delete`, with the user, bucket, path, size and IP). Rejections by policy are not stored in your database.
- **Errors in the SDK.** The SDK throws an `Error` with the server's text (`Upload not allowed by bucket policy`); the `code` does not reach the `Error`. To tell cases apart, call the API directly (`POST /api/bucket/upload`) or compare the message.
- **`PUT` signed URLs.** They remain `service_role` only, even when an `upload` policy exists: the upload goes straight to storage without passing through the maximum size or the quota, and an already issued URL cannot be revoked. To upload with the user's session use `upload()`.

#### When a permission change takes effect

| Change | Effect on writes with a token |
|---|---|
| Create, change or delete a policy (dashboard or CLI) | Immediate; at most 60 s if your API runs in several processes |
| Remove a role or permission, deactivate, reactivate or delete a user with the admin API | Immediate on the process that handles the call; up to 2 minutes if your API runs in several processes |
| Change the roles and permissions tables, or deactivate a user, with direct SQL on `AUTH_USERS` and the other tables | Up to 2 minutes |
| Sign out (`signOut`) | None until the access token expires (up to 1 hour by default): signing out only revokes the refresh token |
| Revoke the `anon` key | Immediate |

To cut a user's access as soon as possible, deactivate them with the admin API (and, with several processes, allow up to 2 minutes).

### Who can read

Without a `read` policy, any user with a session in the project (`anon` key + valid token) can download any file in any bucket, and so can `service_role`. That is the default even if you have `own-folder` write policies: if user A knows the path of one of user B's files, they can download it.

To restrict reading, define a `read` policy (same scopes and permissions as above). With it, downloads and `GET` signed URLs with a token go through the policy (`403` `STORAGE_POLICY_DENIED`, `Read not allowed by bucket policy`); `service_role` still reads everything. While a `read` policy exists, the lifetime of a `GET` signed URL is capped at 3600 seconds (1 hour). An already issued signed URL cannot be revoked: it keeps working until it expires even if you later change the policy or the user's permission.

### Error codes for writes with a token

| Case | Status | `code` | `error` |
|---|---|---|---|
| `anon` key without a token, or writes with a token disabled | 403 | `FORBIDDEN` | `service_role key required for uploads` / `service_role key required for deletes` |
| `anon` key with an invalid or expired token, from another project, or not an access token | 401 | `AUTH_REQUIRED` | `Valid JWT required for user uploads` / `Valid JWT required for user deletes` |
| Valid token, but the bucket has no policy for that operation | 403 | `FORBIDDEN` | same as the first row |
| Valid token, a policy exists and is not met (missing permission, outside their folder, inactive or deleted user) | 403 | `STORAGE_POLICY_DENIED` | `Upload not allowed by bucket policy` / `Delete not allowed by bucket policy` / `Read not allowed by bucket policy` |
| Too many simultaneous uploads by the same user | 429 | `UPLOADS_BUSY` | the limiter's text, with `Retry-After` |
| `PUT` signed URL with the `anon` key | 403 | `FORBIDDEN` | `service_role key required for write (PUT) signed URLs` |

No response includes the path, the required permission or the internal reason.

### Self-hosted and dedicated installs

On a self-hosted install or a dedicated (BYOC) deployment:

- `STORAGE_USER_WRITES_ENABLED=false` plus a service restart turns off uploads and deletes with a token: `upload` and `delete` policies are ignored and everything requires `service_role` again. It relaxes nothing: `read` policies keep applying (the switch only affects writes).
- **Before rolling back to a version without this feature, read this.** A version older than this feature ignores `read` policies: after the rollback any user with a session can download any file again, including in buckets where you restricted reading (the table stays in the database, but the old code does not consult it). Uploads and deletes with a token do fail closed (they require `service_role` again). So: if you only want to stop writes with a token, use `STORAGE_USER_WRITES_ENABLED=false` instead of rolling back, because it keeps the `read` restrictions; if you really must roll back, do it last, and while the old version is running treat every file as readable by any signed-in user (move sensitive files out of reach or do not roll back).
- `UPLOAD_MAX_PER_USER` changes the per-user simultaneous upload limit (2 by default; an integer of 1 or more).
- On a dedicated deployment (BYOC) each project's storage has no cap by default (plan limits do not apply); the owner can set one from the dashboard. See «Project quotas» in [BYOC and dedicated deployment](/en/docs#byoc-dedicated).
- `GET /api/capabilities` lists `storage-user-writes` in `data.features` when writes with a token are active, so an app can tell whether the instance accepts them.
- An instance older than this feature has no policies: the dashboard and the CLI tell you to update it.


---

# Email


## Transactional email

Send emails from your custom domain. Kronbase uses OCI Email Delivery — messages are sent *FROM* your project's approved address.

### Prerequisite

> **Note:** First configure and verify your domain in the dashboard (Email tab → Custom domain). Once the DKIM (the CNAME) is verified, the sender `noreply@yourdomain.com` is approved and ready.

### Adding the domain: timing and errors

Creating the domain in OCI Email Delivery can take up to a minute. `POST .../email/domain` waits a few seconds: if OCI has already activated the domain it answers `200` with the DNS record (`dns: { type, name, value }`); if not yet, it answers `202` with `status: "CREATING"` and `dns: null`. In that case the dashboard shows "Creando el dominio en OCI…" (creating the domain in OCI) and polls the state every few seconds; `GET .../email/config` and `POST .../email/domain/verify` advance the setup (they create the DKIM once the domain is active) and return the record as soon as it is ready. The domain name is normalised (lowercase, no trailing dot). If the domain is not ready after ~3 minutes the dashboard stops polling and offers "Actualizar" (refresh). Repeating the same `POST` (for example after a proxy 504) is idempotent: it returns or advances the setup in progress without deleting it. If a setup stays incomplete for more than ~5 minutes (OCI does not accept the DKIM or does not publish its DNS record) it becomes `FAILED` and you can use "Volver a crear" (re-create). When you delete a verified domain the project falls back to the default sender (if the instance has one) immediately, even if OCI takes longer to finish the deletion. Re-adding the domain is safe: if an earlier attempt failed halfway, Kronbase reuses or cleans up what was left in OCI; a reused domain always gets a new DKIM record and is not marked verified until OCI validates that DNS. If the project already had a domain, it is removed before the new one is created.

The record to create in your DNS is a CNAME whose **name** is the DKIM subdomain (`<selector>._domainkey.yourdomain.com`) and whose **value** is the target OCI gives you (`...dkim....oracleemaildelivery.com`); a TXT record (`dns.type`) is returned only when OCI offers no CNAME. Domains added with an earlier version fix their name and value automatically when you open the Email tab or verify.

Common errors when adding it:

- `409` "Ese dominio ya existe en OCI Email Delivery en este compartimento" (the domain already exists in OCI Email Delivery in this compartment).
- `409` "El dominio ya está registrado en otro proyecto" (the domain is already registered for another project; a domain cannot be shared between projects).
- `409` "Ya hay una operación de dominio en curso para este proyecto" (another domain operation is in progress for this project; wait for it to finish).
- `409` "Ese dominio se está procesando ahora mismo" (`code: BUSY`): another operation is creating or cleaning up that domain; wait a few seconds and retry.
- `502` for permissions: the API identity needs the IAM policy `Allow group <group> to manage email-family in compartment <compartment>`.
- `502` "OCI Email Delivery no pudo crear el dominio" (`code: DOMAIN_FAILED`): the setup failed in OCI; use "Volver a crear" (re-create) in the dashboard, or delete the domain and add it again.
- `503` "OCI Email Delivery no disponible, reintenta" (rate limit or temporary OCI failure): retry in a few minutes.
- `503` `code: DELETE_PENDING`: the previous domain is still being deleted in OCI (this can take longer than the request). It is not a failure: the record is kept and retrying resumes the deletion.

`POST .../email/domain/verify` also returns `senderApproved` (boolean): whether the sender `noreply@yourdomain.com` is already approved in OCI. If the domain or its DKIM is deleted directly in OCI, verification marks it `FAILED` and the project falls back to the default sender (if the instance has one); re-add the domain to recover.

### Domain DNS records

Besides DKIM, the dashboard (Email tab → Custom domain) lists **all** the DNS records you have to configure, each with copy buttons for name and value and a detection chip. The API returns them as `dnsRecords` (in `GET .../email/config` inside `domain`, and in the responses of `POST .../email/domain` and `POST .../email/domain/verify`); the `dns` field still exists and only describes the DKIM.

| Record | Type | Name | Need |
|--------|------|------|------|
| DKIM | CNAME (or TXT) | `<selector>._domainkey.yourdomain.com` | Required: signs your emails |
| SPF | TXT | `yourdomain.com` | Required for deliverability: authorises OCI to send for your domain |
| DMARC | TXT | `_dmarc.yourdomain.com` | Recommended: delivery policy |

Each `dnsRecords` item has `purpose` (`DKIM`, `SPF` or `DMARC`), `type`, `name`, `value`, `required`, `detected` (`yes`, `no` or `unknown`) and sometimes `note`. While OCI is creating the domain (`CREATING`) the DKIM does not appear yet, but SPF and DMARC do.

**SPF.** The value depends on the instance's OCI Email Delivery region, per [Oracle's table](https://docs.oracle.com/en-us/iaas/Content/Email/Tasks/configurespf.htm):

| Regions | SPF value |
|---------|-----------|
| Americas (`us-`, `ca-`, `sa-`, `mx-`, `br-`) | `v=spf1 include:rp.oracleemaildelivery.com ~all` |
| Asia/Pacific (`ap-`) | `v=spf1 include:ap.rp.oracleemaildelivery.com ~all` |
| Europe (`eu-`, `uk-`) | `v=spf1 include:eu.rp.oracleemaildelivery.com ~all` |
| Middle East, Africa and Israel (`me-`, `af-`, `il-`) or no region set | `v=spf1 include:rp.oracleemaildelivery.com include:ap.rp.oracleemaildelivery.com include:eu.rp.oracleemaildelivery.com ~all` (all commercial regions) |
| Government, sovereign or dedicated realms (e.g. `eu-frankfurt-2`, `eu-madrid-2`, `uk-gov-*`, `us-gov-*`, `us-langley-1`, `us-luke-1`, Japan dedicated) or any region not known to be commercial | No include is shown: the record is different, see [Oracle's documentation](https://docs.oracle.com/en-us/iaas/Content/Email/Tasks/configurespf.htm). SPF appears as "Recomendado" (recommended) with no detection |

A domain can have only **one** `v=spf1` record (with two, SPF fails for all mail, RFC 7208, and it is shown as not detected with a warning): if you already have one, do not create a second; merge OCI's `include:` into the existing one (for example `v=spf1 include:_spf.google.com include:rp.oracleemaildelivery.com ~all`).

**DMARC.** `v=DMARC1; p=none` at `_dmarc.yourdomain.com` is suggested. With `p=none` it only monitors: it does not block or send to spam. You can add `rua=mailto:you@example.com` to receive aggregate reports and tighten the policy (`quarantine`, `reject`) once you are sure all your legitimate mail passes SPF or DKIM. If you already have a DMARC record it is respected and shown as detected. If the subdomain has no DMARC of its own but its parent domain does (e.g. `_dmarc.datum.com.gt` for `kron.datum.com.gt`), it is shown as detected "inherited" and `p=none` is not suggested: publishing it on the subdomain would replace the parent's policy. Two DMARC records at the same name are all ignored and a warning is shown.

**What counts for "Verified".** Only DKIM: the `VERIFIED` status depends solely on OCI validating the DKIM. SPF and DMARC never change the domain status or the approved sender; they improve deliverability.

**Detection.** The API queries public DNS from its instance and the dashboard shows one chip per record: "Detectado" (detected: SPF only if there is a `v=spf1` that includes OCI's host; DMARC if there is a `v=DMARC1`; DKIM if it matches the expected value), "No detectado" (not detected) or "No se pudo comprobar" (could not be checked, `unknown`: the lookup failed or timed out, or OCI's include may sit inside another `include`/`redirect` that is not resolved; not an error). OCI's include is matched case-insensitively and with or without a trailing dot. If an SPF with no includes that does not include OCI already exists, the note "Ya existe un SPF que no incluye OCI: fusiona el include" is shown. The lookup is done by the instance with its own DNS resolver (on a dedicated deployment, your VCN's), so it can differ from public DNS: if the status is `VERIFIED` in OCI, the DKIM is fine even if it shows "No detectado" here. Results are cached for about 60 s per domain and record, and detection never blocks or fails the endpoint. If your SPF already uses several DNS-querying mechanisms, a note warns about the 10-lookup limit (RFC 7208). `GET .../email/config?refresh=1` skips that cache for the domain (at most once per ~10 s per domain; otherwise the cache is served); "Comprobar de nuevo" uses it. DNS propagation can take from minutes to a few hours: after adding a record, press "Comprobar de nuevo" (re-reads the configuration). As a secondary hint, if OCI reports the domain's `isSpf` a note is added, but detection does not depend on it.

### Send an email with the SDK

```typescript
import { createClient } from '@kronbase/client'

// The client authenticates with your project's API key
const kb = createClient(
  process.env.KB_URL!,
  { accessToken: process.env.KB_API_KEY! }
)

const result = await kb.email().send({
  to:      { email: 'customer@example.com', name: 'María López' },
  subject: 'Your order has been confirmed',
  bodyHtml: `
    <h2>Thank you for your purchase!</h2>
    <p>Your order #1234 is on its way.</p>
  `,
}).execute()

// result.from          → noreply@yourdomain.com
// result.monthly.used  → emails sent this month
// result.monthly.limit → the plan's monthly limit (on BYOC / dedicated deployment, null unless the project has a cap)
```

### With CC and reply-to

```typescript
await kb.email().send({
  to:      { email: 'client@example.com' },
  subject: 'Quote',
  bodyHtml: '<p>Here is the quote you asked for.</p>',
  replyTo: { email: 'sales@yourdomain.com', name: 'Sales Team' },
  cc:      [{ email: 'support@yourdomain.com' }],
}).execute()
```

`replyTo` takes one address (`{ email, name? }`) or a list of 1 to 5. Repeated addresses (case-insensitive) are sent once; an empty list or one with more than 5 returns `400`. If you do not send `replyTo`, the project's configured reply-to (dashboard → Email) is used, if any.

```typescript
replyTo: [
  { email: 'sales@yourdomain.com', name: 'Sales' },
  { email: 'support@yourdomain.com' },
],
```

The names in `to`, `cc` and `replyTo` are sanitized with the same rule as the sender name (see "Display name"): line breaks, control and invisible characters, double quotes, `<`, `>` and `\` are removed, and they are cut to 100 characters. `,`, `;` and `@` are removed too, so a name never looks like another address (`Pérez, Juan` is sent as `Pérez Juan`). A name that ends up empty is dropped and only the address is sent.

> **Note:** An older API only accepts `replyTo` as a single object: a list returns `400`. On a self-hosted or BYOC deployment, update the instance (**Update** button in the dashboard).

### Attachments

```typescript
import { readFile } from 'node:fs/promises'

await kb.email().send({
  to:      { email: 'client@example.com' },
  subject: 'Your invoice',
  bodyHtml: '<p>Your invoice is attached.</p>',
  attachments: [{
    filename:    'invoice-1234.pdf',
    content:     (await readFile('invoice-1234.pdf')).toString('base64'),
    contentType: 'application/pdf',
  }],
}).execute()
```

Each attachment has:

- `filename`: the name the recipient sees. It is sanitized: the path is removed (only the last segment is kept, no `..`), as are line breaks, control characters, invisible format characters (zero-width, bidi, variation selectors…) and fillers that render blank (blank braille pattern, Hangul fillers); quotes and `< > : * ? | ;` become `_`; leading dots and trailing dots or spaces are removed, and it is cut to 100 characters keeping the extension (after the cut it is cleaned again, and the extension is checked on that final name, which is the one sent). If nothing is left, or if the name has a lone UTF-16 surrogate (malformed text), the API returns `400` `INVALID_ATTACHMENT`.
- `content`: the file in standard base64, without line breaks or spaces (for example `buffer.toString('base64')` in Node). Invalid or empty base64 returns `400`.
- `contentType`: the MIME type, `type/subtype` (for example `application/pdf`, `image/png`, `text/csv`). The only parameter allowed is `charset` (`text/plain; charset=utf-8`).

**Default limits:**

| Limit | Value |
|---|---|
| Attachments per send | 5 |
| Size per file (decoded) | 1 MiB (1,048,576 bytes) |
| Total size of the attachments (decoded) | 1 MiB (1,048,576 bytes) |
| Size of the whole message (headers, HTML and encoded attachments) | 2,000,000 bytes |

The message size is measured as it is encoded for sending: attachments take about 4/3 of their size (base64) and the HTML between 1 and about 3 times its bytes, depending on the content: HTML with many non-ASCII characters or many `=` takes more once encoded. If it does not fit, the API returns `413` `EMAIL_TOO_LARGE` without sending. **This maximum message size also applies to sends without attachments.** On self-hosted or BYOC you can change them with the API environment variables `EMAIL_ATTACHMENTS_MAX_COUNT` (`0` turns attachments off; default `5`), `EMAIL_ATTACHMENT_MAX_BYTES` (default `1048576`), `EMAIL_ATTACHMENTS_MAX_TOTAL_BYTES` (default `1048576`) and `EMAIL_MAX_MESSAGE_BYTES` (default `2000000`); the three `*_BYTES` variables are in bytes; the last one must not exceed your transport's maximum message size (OCI Email Delivery limits the message size; check your tenancy's service limits before raising it).

**Blocked types.** Executables, scripts, installers, shortcuts, Office add-ins, Access databases, disk images and certificates are not accepted. The last extension of the final name is checked, case-insensitively and also in its normalized form (NFKC and case folding, so `a．ｅｘｅ` or `a.ſh` are rejected too; the name that is sent does not change): `exe`, `ex`, `ex_`, `com`, `scr`, `pif`, `cpl`, `dll`, `lib`, `sys`, `drv`, `vxd`, `ocx`, `cab`, `msi`, `msp`, `mst`, `msu`, `msc`, `msix`, `msixbundle`, `appx`, `appxbundle`, `application`, `appref-ms`, `appinstaller`, `xbap`, `gadget`, `diagcab`, `diagcfg`, `diagpack`, `wim`, `lnk`, `scf`, `url`, `website`, `shb`, `inf`, `ins`, `isp`, `reg`, `hta`, `chm`, `hlp`, `settingcontent-ms`, `library-ms`, `bat`, `cmd`, `js`, `jse`, `mjs`, `htc`, `bas`, `vb`, `vbs`, `vbe`, `wsf`, `wsh`, `ws`, `wsc`, `sct`, `nsh`, `ps1`, `ps1xml`, `ps2`, `ps2xml`, `psc1`, `psc2`, `psm1`, `psd1`, `msh`, `msh1`, `msh2`, `mshxml`, `msh1xml`, `msh2xml`, `shs`, `sh`, `bash`, `zsh`, `csh`, `ksh`, `command`, `py`, `pyc`, `pyw`, `pyo`, `pl`, `xll`, `xlam`, `ade`, `adp`, `mde`, `mdb`, `accde`, `iqy`, `slk`, `one`, `cer`, `crt`, `der`, `jar`, `jnlp`, `app`, `dmg`, `pkg`, `apk`, `deb`, `rpm`, `iso`, `img`, `vhd` and `vhdx`. Executable and script `contentType`s are rejected too (for example `application/x-msdownload`, `application/javascript`, `text/javascript`, `application/java-archive`, `application/x-sh`), as are the `multipart/*` and `message/*` families. If you need to share one of these files, upload it to Storage and send a link.

**Quota and errors.** A send with attachments counts as one email in the monthly quota. Attachments are validated first: a rejection does not consume quota or send anything. The content is not stored or written to the log.

| HTTP | `code` | When |
|---|---|---|
| `400` | `TOO_MANY_ATTACHMENTS` | More attachments than the maximum (or attachments turned off on the instance) |
| `400` | `INVALID_ATTACHMENT` | `filename` empty after sanitizing, `content` that is not valid base64, or a `contentType` that is not `type/subtype` |
| `400` | `ATTACHMENT_TYPE_NOT_ALLOWED` | Blocked extension or MIME type |
| `413` | `ATTACHMENT_TOO_LARGE` | A file exceeds the per-file maximum |
| `413` | `ATTACHMENTS_TOO_LARGE` | The attachments add up to more than the allowed total |
| `413` | `EMAIL_TOO_LARGE` | The encoded message (headers, HTML and attachments) exceeds the maximum size, or the request is too large |

The error message names the attachment (`attachments[1] ("data.exe"): …`, in Spanish). With the SDK, `execute()` throws an `Error` with that message plus `status` and `code`.

> **Note:** An older API silently drops `attachments` and would send the email without them. So, when there are attachments, the SDK first checks `GET /api/capabilities` (once per URL) and, if the server does not advertise `email-attachments`, fails with the code `EMAIL_ATTACHMENTS_UNSUPPORTED` without sending anything. On a self-hosted or BYOC deployment, update the instance. Sends without attachments skip this check.

### Error handling

```typescript
// HTTP 400 — domain not verified
{ "error": "El dominio de email no está verificado", "code": "DOMAIN_NOT_VERIFIED" }

// HTTP 429 — monthly limit reached
{ "error": "Límite mensual alcanzado (100 emails/mes)...", "code": "MONTHLY_LIMIT_REACHED",
  "monthly": { "used": 100, "limit": 100, "resetsAt": "..." } }

// HTTP 401 — invalid API key
{ "error": "API key inválida o revocada", "code": "INVALID_KEY" }

// HTTP 503 — the instance has no usable email transport
{ "error": "El transporte de email de esta instancia no está disponible. ...", "code": "EMAIL_TRANSPORT_UNAVAILABLE" }

// HTTP 413 — attachments too large (see "Attachments")
{ "error": "Los adjuntos suman 1.5 MB; el máximo por envío es 1 MB.", "code": "ATTACHMENTS_TOO_LARGE" }
```

With the SDK, `kb.email().send(...).execute()` throws an `Error` with the API message, `status` (HTTP code), `code` and, on `429`, `monthly`. If the response is not JSON (for example a `413` from a proxy), the message gives the HTTP code.

A send that fails with `EMAIL_TRANSPORT_UNAVAILABLE` does not consume the monthly quota. The detail (SMTP server or missing variable) is only written to the API log. `kb.email().send()` always sends from the project's verified domain: without one it answers `DOMAIN_NOT_VERIFIED`. The `EMAIL_NO_SENDER` code (`400`) is returned by the dashboard test email and by `POST /auth/invite` (see "Senders").

The `error` messages shown are the literal strings returned by the API (in Spanish); rely on the `code` field in your code.

### Upload templates in bulk

The Auth emails (`invite`, `password_reset`, `otp_code`, `otp_magic_link`, `otp_combined`) can be customised per project. To upload several at once (for example from your repository) use the bulk endpoint, or `kronbase templates push` (see `CLI`):

```bash
curl -X PUT "https://api.kronbase.dev/platform/customers/me/projects/$PROJECT_ID/email/templates" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{ "templates": [
        { "key": "invite", "subject": "You are invited", "bodyHtml": "<p>Join here: <a href=\"{{link}}\">sign in</a></p>" },
        { "key": "otp_code", "subject": "Your code", "bodyHtml": "<p>Code: {{code}}</p>" }
      ] }'
```

> **Note:** Platform routes are mounted at the root (`https://api.kronbase.dev/platform/...`), not under `/api` like the `KB_URL` of the other examples. `$TOKEN` is your account session token (the one `kronbase login` stores in `~/.kronbase/credentials.json`); it is not a project JWT or an API key. `$PROJECT_ID` is the project UUID (the `projectId` field of `GET /platform/customers/me/projects`), not the slug. The easiest route is `kronbase templates push`, which resolves all of this for you.

```json
// HTTP 200 — created: true if the template did not exist yet
{ "success": true, "data": [
  { "key": "invite", "subject": "You are invited", "bodyHtml": "...", "created": false,
    "removed": { "tags": ["script"], "attributes": ["onclick"] } },
  { "key": "otp_code", "subject": "Your code", "bodyHtml": "...", "created": true,
    "removed": { "tags": [], "attributes": [] } } ] }

// HTTP 400 — nothing was saved; one error per invalid template
{ "error": "Hay plantillas inválidas; no se guardó ninguna.",
  "errors": [ { "index": 1, "key": "otp_code", "error": "El HTML no puede quedar sin {{code}} — el email quedaría roto." } ] }
```

- 1 to 5 templates per request (there are 5 keys and each may appear only once; a repeated key is an error). A customized template is unique: it has no per-language variants.
- Each template is validated like `PUT .../email/templates/:key`: subject of 1 to 255 characters, sanitized HTML and required placeholders (`{{link}}`, `{{code}}`).
- It is **all-or-nothing**: everything is validated before anything is written and the writes run in a single transaction; if anything fails, nothing is saved.
- Same credentials and project ownership as the single-template route.

> **Note:** Templates you leave out of the batch are untouched: the batch creates or updates, it never deletes.

#### What sanitizing removes (`removed`)

The HTML is stored sanitized. Allowed tags are `html`, `head`, `meta`, `body`, `table`, `tr`, `td`, `div`, `span`, `p`, `a`, `strong`, `em`, `br` and `img`; allowed attributes are `style`, `class`, `width`, `height`, `align`, `cellpadding` and `cellspacing` on any of them, plus `charset`/`name`/`content` on `meta`, `lang` on `html`, `href` on `a` and `src`/`alt` on `img`. `href` and `src` only accept `http`, `https` and `mailto` (an `href="javascript:…"` or a `src="data:…"` is removed). Everything else is removed: a disallowed tag keeps its text, except `script`, `style`, `textarea`, `option` and `xmp`, whose whole content is dropped; HTML comments are removed too.

`PUT .../email/templates/:key` (in `data`) and the batch (in each element of `data`) return `removed`, listing what was removed:

- `removed.tags`: names of the removed tags.
- `removed.attributes`: names of the attributes removed from tags that were kept (attributes of a removed tag are not repeated here).

They are only names (lowercase, no duplicates, alphabetical, up to 50 per list and 40 characters per name), never values or text from your template. If no tag or attribute was removed both lists are empty, even though `bodyHtml` may differ because of removed HTML comments (not listed) or changes of form: quotes, entities, `<br />`. Older APIs do not send `removed`: treat it as optional. `kronbase templates push` and the dashboard use it to tell you what was removed.
### Limits per plan

| Plan | Sends / month | Custom domain |
| --- | --- | --- |
| Free | 100 | ✓ |
| Starter | 1,000 | ✓ |
| Pro | 10,000 | ✓ |

These limits apply on Kronbase Cloud. The quota renews on the 1st of each month (UTC); `GET .../email/config` and `kb.email().send()` return the next renewal in `monthly.resetsAt` as a date (`YYYY-MM-DD`). On BYOC / dedicated deployments there is no monthly cap by default: `monthly.used` is still counted for information, and `monthly.limit` and `monthly.resetsAt` are `null`. The owner can set a cap per project (see «Project quotas» in [BYOC and dedicated deployment](/en/docs#byoc-dedicated)); it then applies as on Cloud.

### Senders

There are two sender levels:

1. **Project domain.** If the project has a verified domain, all its emails (`POST /api/email/send`, authentication emails and the dashboard test email) are sent from `noreply@yourdomain.com`.
2. **Instance default sender** (`OCI_EMAIL_SENDER` and `OCI_EMAIL_SENDER_NAME`, optional). It is only used for authentication emails and the test email of projects without a verified domain, and for the platform's own emails (account notices, new-version notices or administrator alerts).

OCI Email Delivery is enabled by the OCI credentials (`OCI_TENANCY_ID`, `OCI_USER_ID`, `OCI_FINGERPRINT`, `OCI_PRIVATE_KEY`, `OCI_REGION`) plus a compartment (`OCI_COMPARTMENT_ID` or `OCI_EMAIL_COMPARTMENT_ID`). Each send uses the compartment where its sender is approved: project-domain senders are created in `OCI_COMPARTMENT_ID`; `OCI_EMAIL_COMPARTMENT_ID` only applies to the default sender. If you set only one of them, it is used for both. The default sender is no longer required: without it, projects with a verified domain send normally, and a project without a verified domain gets `EMAIL_NO_SENDER` until it adds and verifies one (the dashboard shows "Agrega y verifica un dominio para poder enviar correos"; `GET .../email/config` returns `defaultSenderConfigured: false`). Kronbase never sends from a made-up address. Without a default sender, platform emails are skipped and logged.

On BYOC / dedicated deployment, the stack passes `OCI_COMPARTMENT_ID` automatically and configures no default sender: email works with only a verified project domain. The default sender can be added by hand (see [BYOC and dedicated deployment](/en/docs#byoc-dedicated)).

If the OCI credentials are not configured, the API uses SMTP (`MAIL_SMTP_HOST`/`MAIL_SMTP_PORT`, `localhost:1025` by default), as in `kronbase start`. If OCI credentials are present but the compartment is missing, email is disabled (it does not silently fall back to SMTP) and the API log says what is missing. If the SMTP server does not answer, sending fails with `EMAIL_TRANSPORT_UNAVAILABLE` (`503`); for authentication emails, OTP and password reset still answer success to the caller (the failure is logged) and invite answers `503`. With `MAIL_TRANSPORT=oci` the API requires OCI and, if something is missing, the startup error lists the missing variables.

### Authentication emails

Authentication emails (OTP code, magic link, password reset and invitations) follow the same sender rule. If your project has a verified domain, they are sent from `noreply@yourdomain.com` (with your display name and reply-to, if configured). If sending with that sender fails, **the email is not sent**: Kronbase never falls back to the platform sender, so no message from your app arrives from a domain that is not yours. The failure is logged by the API with the code `AUTH_EMAIL_SENDER_FAILED`. To avoid revealing whether a user exists, `POST /auth/otp/send` and `POST /auth/password-reset/request` still answer success to the caller even when sending fails; `POST /auth/invite` (service key) answers 500 with the failure code: `AUTH_EMAIL_SENDER_FAILED`, or `AUTH_EMAIL_SENDER_UNSUPPORTED` when the transport does not support the project sender. Projects without a verified domain keep sending from the instance default sender; if the instance has no default sender, the email is not sent and the log records `EMAIL_NO_SENDER` (`POST /auth/invite` answers `400` with that code; OTP and password reset still answer success to the caller). The sender is always read from the project configuration, never from the request, and domain or email-config changes take effect as soon as they are saved (the sender is cached for about 60 s per API instance). It does not apply in local dev (`LOCAL_DEV=true`). The sender name follows the «Display name» rule (below). These emails do not count toward the monthly send quota. If the active transport cannot send with the project sender (SMTP outside local dev), the email is not sent either and the log records `AUTH_EMAIL_SENDER_UNSUPPORTED`. A sender that is not yet approved in OCI does not count: the default sender is used meanwhile, and verifying the domain again retries approving it.

### Email language

Each project sends its authentication emails and the test email in **Spanish** (`es`) or **English** (`en`). Choose it in the dashboard (*Email → Templates → Email language*) or through the API:

```bash
# es or en
curl -X PUT "https://api.kronbase.dev/platform/customers/me/projects/$PROJECT_ID/email/language" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{ "language": "en" }'
```

Projects created from the dashboard take its language; all others (CLI, API and existing ones) use Spanish. When creating a project through the API you can send `emailLanguage`. The language applies to the default templates: a template you customized is sent exactly as you wrote it. A dedicated deployment needs an API version that supports this option.

### Display name

The name shown next to your sender (`"Name" <noreply@yourdomain.com>`) and the value of `{{projectName}}` in the subject and body of authentication emails (and the project name in the dashboard test email) follow the same rule:

1. The project's email **display name** (dashboard → Email → «Nombre del remitente», `kronbase email config --display-name` or `displayName` in `PUT .../email/config`), if you set one.
2. Otherwise, the project's **visible name** (the one you gave it when you created it).

The slug or any other technical identifier is never used. If your emails show a name you did not expect, check those two fields: the visible name is used until you set a display name.

The name is always sanitized before use: line breaks and other control characters, invisible and direction-control characters (for example zero-width or bidi), double quotes, `<`, `>` and `\` are removed, repeated spaces collapse to one, and it is cut to 100 characters. When saving, `displayName` accepts up to 100 characters with no line breaks.

This applies to the emails sent from your verified domain (`kb.email().send()`, authentication emails and the test email). Emails of a project **without** a verified domain go out from the instance default sender and carry its name (`OCI_EMAIL_SENDER_NAME`), although `{{projectName}}` in the body is still the project's name. If a template gets no name, `{{projectName}}` reads «your app» («tu aplicación» in Spanish).

### Authentication email links and branding

Every link in an authentication email points to your project's base URL (`base_url`, set in the dashboard → Email, with `kronbase email config --base-url` or with `baseUrl` in `PUT .../email/config`) in this format:

```text
<base_url>?token=<token>&type=<type>
```

| Email | How it is sent | `type` | URL override |
|---|---|---|---|
| Invitation | `POST /auth/invite` (`kb.auth().inviteUser()`, service key) | `invite` | `invite` |
| Password reset | `POST /auth/password-reset/request` (`kb.auth().requestPasswordReset()`) | `recovery` | `reset` |
| Magic link | `POST /auth/otp/send` with `type: 'magic_link'` (`kb.auth().sendOtp(email, 'magic_link')`) | `magiclink` | `magic_link` |
| Code + link | `POST /auth/otp/send` with `type: 'combined'` | `magiclink` | `otp` |
| Code only | `POST /auth/otp/send` with `type: 'code'` (`kb.auth().sendOtp(email)`: the SDK's default type) | no link | — |

- With a single `base_url` your app receives every link and picks the screen from `type`. If you want a different route per email, set a per-type override (`baseUrls` in `PUT .../email/config`, or `kronbase email config --invite-url/--reset-url/--magic-link-url/--otp-url`); a type without an override uses the `base_url`. Details and URL validation in [Auth](/en/docs/auth).
- If the `base_url` already has a query string, `token` and `type` are appended with `&`.
- Always set a `base_url`: without one the link has no address (only `?token=…&type=…`), unless the instance has a default one.
- There is no separate "verify your email" message: verifying an OTP code or a magic link marks the user with `emailVerified: true`.
- `POST /auth/otp/send` only sends when the user already exists (it does not create accounts) and answers the same success (`200`, `{ "success": true }`) whether or not the user exists, and also when sending the email fails, so it does not reveal which emails are registered. Other responses: `400` if the body is invalid, `429` `RATE_LIMITED` above 3 sends per minute from the same IP (default limit; the instance can scale it), and `500` `OTP_SEND_ERROR` on an unexpected server error (or `503` `DB_POOL_EXHAUSTED` / `500` `DB_ERROR` if the database fails while looking up the email). The response goes out after looking up the email, before the code is stored and the email is sent, so it takes the same time whether or not the account exists: the email may arrive a moment later, and a failure while storing or sending it only shows up in the API log. The same applies to `POST /auth/password-reset/request`.

**What can be chosen per call.** `kb.auth().sendOtp(email, type)` takes only the email and the type (`'code'`, `'magic_link'` or `'combined'`; if you omit it, the SDK sends `'code'`); `POST /auth/otp/send` requires `email` and `type` (no default) and any other body field is ignored. Invite (`userId`, `email`) and password reset (`email`) do not take link or branding options either. Today there is **no** per-call redirect URL, template, subject, language, sender or name: everything comes from the project configuration:

- the link URL: `base_url` and its per-type overrides;
- the content: the project's templates (`invite`, `password_reset`, `otp_code`, `otp_magic_link`, `otp_combined`; one per type, no per-language variants) or the default ones, in the project's email language;
- the sender and the name: see «Senders» and «Display name».

Variables available in templates: `{{projectName}}` in all of them; `{{link}}` in `invite`, `password_reset`, `otp_magic_link` and `otp_combined`; `{{code}}` in `otp_code` and `otp_combined`; `{{minutes}}` (validity) in the OTP ones and `{{expiresHours}}` in `invite` and `password_reset`. Values are inserted escaped in the HTML.

### Local dev (`kronbase start`)

In the `kronbase start` local stack (API with `LOCAL_DEV=true`), emails go to Mailpit and never leave your machine, so `POST /api/email/send` (`kb.email().send()`) and the dashboard test email do not require a verified domain and do not consume the monthly quota: they never answer `DOMAIN_NOT_VERIFIED` or `MONTHLY_LIMIT_REACHED`. When no domain is configured, the sender is the local SMTP one (`MAIL_FROM_EMAIL`, `noreply@localhost` by default), and `monthly` reports the counter without incrementing it. On Kronbase Cloud the verified domain and the quota are always enforced; on BYOC / dedicated deployments the verified domain is enforced, with no monthly cap unless the project has one.


---

# Auth model


## Auth model

Every request to the Data API (`https://api.kronbase.dev/api`) is authenticated in two layers. The first identifies the **project**; the second, optional for server keys, identifies the **end user**.

| Layer | Where it goes | What it proves |
|---|---|---|
| Project API key | `x-api-key: <key>` header | Which project (and Oracle schema) the request targets, and the key type (`anon` or `service_role`) |
| User access token (JWT) | `Authorization: Bearer <accessToken>` header | Which end user is making the request |

A request without `x-api-key` is rejected with `401` and code `API_KEY_REQUIRED`; an unknown or revoked key returns `401` with `INVALID_API_KEY`.

### API keys

Each key has a type that the server resolves by looking the key up, not from the header name.

| Type | Intended use | Behavior |
|---|---|---|
| `anon` | Browser and mobile apps | Queries need a valid user JWT, except `SELECT` on tables marked public in your project |
| `service_role` | Your backend only | Does not require a JWT, bypasses row-level security (RLS) and can use admin-only operations. It is the only key that uploads and deletes in buckets that have no bucket policy (see [Storage](/en/docs#storage)) |

New keys carry a prefix by type, so you can tell them apart at a glance:

| Type | Prefix | Example |
|---|---|---|
| `anon` | `kb_anon_` | `kb_anon_x4Jq…` |
| `service_role` | `kb_service_` | `kb_service_9mTa…` |

A `service_role` key must never be exposed in browser or mobile code: use it only in your backend. A `kb_service_` key must not appear in a frontend bundle or in `NEXT_PUBLIC_*` variables. Keys created before this change keep their `pk_` prefix and keep working unchanged: the server resolves them by the full key, not by the prefix.

```typescript
import { createClient } from '@kronbase/client'

// Browser: anon key. All three options are sent in the same x-api-key header.
const kb = createClient('https://api.kronbase.dev/api', { apiKey: 'KB_ANON_KEY' })

// Server: service_role key. Never ship it to the browser.
const admin = createClient('https://api.kronbase.dev/api', { serviceKey: 'KB_SERVICE_KEY' })
```

`apiKey`, `serviceKey` and `anonKey` are aliases in `ClientConfig`: whichever is set is sent as `x-api-key`. The base URL may be given with or without the `/api` suffix; the client adds it if missing.

Rules the server applies by key type:

- With an `anon` key and no `Authorization` header, only `SELECT` on a public table is allowed. Any other operation returns `403` with `READONLY_PUBLIC_TABLE`; a non-public table returns `401` with `AUTH_REQUIRED`.
- With an `anon` key and an invalid or expired token, the response is `401` with `INVALID_TOKEN`.
- Auth-internal tables (`AUTH_USERS`, `AUTH_SESSIONS`, `AUTH_REFRESH_TOKENS`, `AUTH_AUDIT_LOG`, `AUTH_OTP_TOKENS`, `AUTH_TOTP_CONFIG`, `AUTH_INVITE_TOKENS`, `AUTH_IDENTITIES`, `AUTH_WEBHOOK_ENDPOINTS`, `AUTH_WEBHOOK_DELIVERIES`) can never be read or written through the query builder or realtime, with any key (`403`, `AUTH_TABLE_RESTRICTED`; in realtime it arrives as an `error` message). The RBAC tables (`AUTH_ROLES`, `AUTH_PERMISSIONS`, `AUTH_ROLE_PERMISSIONS`, `AUTH_USER_ROLES`, `AUTH_USER_PERMISSIONS`) require a `service_role` key.
- Realtime (WebSocket) applies the same rules and the same RLS: with `service_role` you see everything; with `anon` and no token only public tables; with `anon` plus the user's JWT, that user's RLS view (Realtime section).
- `POST /api/transaction` has no public-table exception: with an `anon` key it always requires a Bearer token.

> **Note:** These rules apply to every table the query references, not only the main one: they also apply to the tables in `joins`. An auth-internal table can never be queried or joined with any key, an RBAC table can only be joined with a `service_role` key, and without a token (`anon` key) every referenced table, including joined ones, must be public (otherwise `401` with `AUTH_REQUIRED`). A qualified column (`X.COLUMN`) must use as `X` one of the query's own tables (the main one or one in `joins`), or its alias when one is declared (otherwise `403` with `INVALID_COLUMN_QUALIFIER`). Write operations (`UPDATE`, `DELETE`, `INSERT`, `UPSERT`) do not support `joins` (`403` with `INVALID_JOIN_OPERATION`); in `UPDATE`/`DELETE` columns are qualified with the table's declared alias or, without one, its name, and in `INSERT`/`UPSERT` they are not qualified. Every column reference is emitted qualified with an internal alias, so a name that Oracle would resolve as a function cannot be called as a column. When the query has `joins`, every column must be qualified with its table or alias (otherwise `403` with `UNQUALIFIED_COLUMN_WITH_JOIN`); `orderBy` and `groupBy` also accept the `select` labels `as X` (applied to their source column), and `orderBy` accepts an aggregate alias and the name of a qualified `select` column that is not repeated. The aliases you declare are used only to reference columns in your request; the generated SQL uses internal aliases. The names `KB_A<n>`, `KB_T` and `KB_S` are reserved for those internal aliases. Columns inside `select()` expressions follow the same rules (qualified with `joins`, declared qualifier, emitted with internal aliases) and functions come from a closed list; see the "Expressions in SELECT" section of the database documentation.

JOIN types in `joins[].type` (upper or lower case): `INNER`, `LEFT`, `RIGHT` and `FULL OUTER`; `FULL` is a synonym of `FULL OUTER` (in the SDK: `innerJoin`, `leftJoin`, `rightJoin` and `fullJoin`). Any other type answers with an `Invalid JOIN type` error. Each JOIN needs at least one condition in `conditions` (an empty array answers `400`).

### Access token (JWT)

The access token is a JWT signed with HS256. It is stateless: the server verifies the signature and expiry without a database lookup.

| Claim | Meaning |
|---|---|
| `sub` | User ID |
| `email` | User email |
| `sessionId` | ID of the session that issued the token |
| `projectId` | Project the token is scoped to |
| `typ` | Always `access` |
| `jti` | Unique token ID |
| `iat`, `exp` | Issued-at and expiry, Unix seconds |

- Lifetime: 3600 seconds (1 hour) by default. The response reports it as `expiresIn` (seconds) and `expiresAt` (ISO timestamp).
- A token is only valid for the project it was issued for. Using it with another project's API key is rejected with `401` on every HTTP endpoint that accepts a user (queries, storage, `/auth/*`, `/auth/permissions`, notifications), as are tokens issued without a `projectId` claim. Realtime has no HTTP response: the `auth` message gets an `error` message with code `INVALID_TOKEN`.
- The intermediate token of the two-factor flow (below) has `typ: "2fa"` and is never accepted as an access token. It is also scoped to its project: it can only be completed with the API key of the project that issued it.

### Refresh token

The refresh token is an opaque UUID, not a JWT. It lives 30 days by default and is stored hashed (SHA-256) on the server, in the database of the project that issued it: with another project's API key it is not found and the refresh fails.

Refreshing rotates it: the old refresh token is revoked and a new pair is returned. Reusing a revoked token fails with `401`.

```bash
curl -X POST https://api.kronbase.dev/api/auth/refresh \
  -H "x-api-key: $KB_ANON_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "refreshToken": "<refreshToken>" }'
```

```json
{
  "success": true,
  "accessToken": "eyJ...",
  "refreshToken": "9f1c...",
  "expiresIn": 3600,
  "expiresAt": "2026-11-03T15:00:00.000Z"
}
```

Errors on refresh return `401` with code `REFRESH_ERROR` when the token is invalid, revoked or expired. Each refresh token works once: if two requests refresh with the same token at the same time, only one gets the new pair and the other gets `401` (token revoked). The same happens if the session is signed out, the password is reset or the account is deactivated while the refresh is in progress.

### Sign up, sign in and sign out

All of these require `x-api-key`.

```bash
# Sign up (also returns a session)
curl -X POST https://api.kronbase.dev/api/auth/signup \
  -H "x-api-key: $KB_ANON_KEY" -H "Content-Type: application/json" \
  -d '{ "email": "user@example.com", "password": "Str0ng!pass", "metadata": { "name": "Ana" } }'

# Sign in
curl -X POST https://api.kronbase.dev/api/auth/signin \
  -H "x-api-key: $KB_ANON_KEY" -H "Content-Type: application/json" \
  -d '{ "email": "user@example.com", "password": "Str0ng!pass" }'

# Current user
curl https://api.kronbase.dev/api/auth/user \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>"

# Sign out (revokes the refresh token)
curl -X POST https://api.kronbase.dev/api/auth/signout \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>" \
  -H "Content-Type: application/json" -d '{ "refreshToken": "<refreshToken>" }'
```

`signup` and `signin` respond with:

```json
{
  "success": true,
  "user": { "id": "...", "email": "user@example.com", "emailVerified": false, "isActive": true, "createdAt": "...", "updatedAt": "...", "metadata": {} },
  "session": { "accessToken": "eyJ...", "refreshToken": "9f1c...", "expiresIn": 3600, "expiresAt": "..." }
}
```

Password rules by default: at least 8 characters, with an uppercase letter, a lowercase letter, a number and a special character from `!@#$%^&*(),.?":{}|<>`. The password is stored hashed with bcrypt.

| Endpoint | Status | Code |
|---|---|---|
| `signup` | `409` email already exists; `400` invalid email or weak password | `SIGNUP_ERROR` |
| `signin` | `401` invalid credentials or disabled account | `SIGNIN_ERROR` |
| `signout`, `user` | `401` invalid or expired token (present but not valid) | `UNAUTHORIZED` |
| `signout`, `user`, `permissions` | `400` when the `Authorization` header is missing altogether (schema validation) | `QUERY_ERROR` |
| `user` | `404` user not found | `USER_NOT_FOUND` |
| any | `429` rate limit exceeded | `RATE_LIMITED` |
| any `/api/auth/*` endpoint | `503` the database is temporarily out of free connections; retry after the seconds in `Retry-After` | `DB_POOL_EXHAUSTED` |
| any `/api/auth/*` endpoint | `500` database error; the detail stays only in the server logs | `DB_ERROR` |
| any `/api/auth/*` endpoint | `500` any other unexpected server error, with a generic message; the detail stays only in the server logs | the endpoint's own code (for example `SIGNIN_ERROR`, `OTP_VERIFY_ERROR`) |

If two sign-ups with the same email arrive at the same time, only one creates the account; the other gets the same `409` `SIGNUP_ERROR` as an already registered email. `signin` takes the same time whether the email does not exist or the password is wrong. A disabled account with a wrong password also answers `Invalid credentials`; `User account is disabled` only appears with the correct password. `otp/verify`, `otp/magic` and `totp/verify` answer `401` with that same message (and their code: `OTP_VERIFY_ERROR`, `MAGIC_LINK_VERIFY_ERROR`, `TWO_FA_VERIFY_ERROR`) when the code is valid but the account is disabled.

Rate limits are per client IP, per minute: sign up 5, sign in 10, OTP send 3, OTP verify 10, magic link 20, 2FA verify 10, password-reset request 5, password-reset confirm 10.

On a self-hosted, BYOC or development instance, the instance operator can tune these limits with API environment variables (on Kronbase Cloud only the Kronbase operator sets them, not each project):

| Variable | Effect |
|---|---|
| `RATE_LIMIT_MULTIPLIER` | Positive number (default `1`) that multiplies every limit above; the result is rounded up and never goes below 1. For example, `10` allows 50 sign-ups per minute instead of 5. An invalid, `0` or negative value uses the default; the maximum is `1000` (a larger value is capped). When it is not 1, the API logs a warning at startup. |
| `RATE_LIMIT_DISABLED` | `true` turns rate limiting off entirely (useful in development or CI; not recommended in production). Takes precedence over `RATE_LIMIT_MULTIPLIER`. |

### Cookies and the SDK

The SDK can keep the session in cookies through a cookie adapter (`getAll()` / `setAll()`). `@kronbase/ssr` provides one for Next.js; see the SSR section. The adapter writes two cookies:

| Cookie | Value | `httpOnly` | `sameSite` | `path` | `maxAge` |
|---|---|---|---|---|---|
| `access_token` | access JWT | `true` | `lax` | `/` | 3600 |
| `refresh_token` | refresh token | `true` | `lax` | `/` | 2592000 |

`createServerClient` from `@kronbase/ssr/server` also sets `secure` when `NODE_ENV` is `production`. In the browser, `createBrowserClient` writes the cookies through `document.cookie`, so `httpOnly` cannot apply there. On sign out both cookies are written empty with `maxAge: 0`.

When a cookie adapter is present, the client attaches `Authorization: Bearer <access_token cookie>` to every request automatically, in addition to `x-api-key`.

```typescript
const user = await kb.auth().getUser()
// { id, email } | null
```

`getUser()` decodes the access token from the cookie locally, with no network call and no signature check. If the token is expired it uses `refresh_token` to refresh and rewrite the cookies, and returns `null` if that fails.

> **Note:** Without a cookie adapter (plain `createClient`), `signIn()`, `verifyOtp()`, `verifyMagicLink()` and `totp.verify()` return only `{ success, user }` and do not give you the tokens. If you manage tokens yourself, call the REST endpoints above, or use `signUp()` / `refreshToken()`, which return the session. You can then pass the token with `createClient(url, { apiKey, accessToken })` for queries, transactions and notifications. The `auth()` helpers (`totp.*`, `signOut()`, `getPermissions()`) build their `Authorization` header only from the cookie adapter's `access_token` cookie and ignore `config.accessToken`, so without a cookie adapter call their REST endpoints directly with the Bearer token.

### Passwordless: OTP code and magic link

`sendOtp(email, type)` sends an email with a code, a link, or both. `type` is `'code'` (default), `'magic_link'` or `'combined'`.

```typescript
await kb.auth().sendOtp('user@example.com', 'combined')

// 6-digit code
const r1 = await kb.auth().verifyOtp('user@example.com', '482910')

// Link: the page that receives ?token=... verifies it
const r2 = await kb.auth().verifyMagicLink(token)
```

```bash
curl -X POST https://api.kronbase.dev/api/auth/otp/send \
  -H "x-api-key: $KB_ANON_KEY" -H "Content-Type: application/json" \
  -d '{ "email": "user@example.com", "type": "code" }'

curl -X POST https://api.kronbase.dev/api/auth/otp/verify \
  -H "x-api-key: $KB_ANON_KEY" -H "Content-Type: application/json" \
  -d '{ "email": "user@example.com", "code": "482910" }'

curl "https://api.kronbase.dev/api/auth/otp/magic?token=<token>" \
  -H "x-api-key: $KB_ANON_KEY"
```

- `otp/send` always answers `{ "success": true }`, even when the email has no account, to avoid revealing which emails exist. The email is only sent if the user exists. So that the response time does not reveal it either, the response goes out before the code is stored and the email is sent, so the email may arrive a moment after the response; a failure in that step only shows up in the server log.
- `otp/verify` and `otp/magic` respond with the same body as `signin` (`user` and `session`). Invalid, used or expired codes return `400` with `OTP_VERIFY_ERROR` or `MAGIC_LINK_VERIFY_ERROR`.
- Default lifetimes: code 15 minutes, magic link 60 minutes. The code has 6 digits.
- Attempts per code: each wrong code submitted against an email's current code (not yet used or expired) adds one attempt on that token. When it reaches `OTP_MAX_ATTEMPTS` (default 5, a server environment variable; an invalid or <= 0 value uses 5) the token is invalidated: even the correct code stops working and a new one must be requested with `otp/send`. A locked token answers like a used or expired code (`400` `OTP_VERIFY_ERROR`; `401` `TWO_FA_VERIFY_ERROR` on `totp/verify`). It also applies to the `email` second-factor method (`totp/verify`). Magic links do not count attempts: their token is 256 random bits and a wrong token matches no row.
- These routes are only available in projects that have email enabled.
- A successful code or magic-link verification sets `emailVerified` to `true` for that user.

#### Existing projects (attempt limit)

New projects are created with the `ATTEMPTS` column in `AUTH_OTP_TOKENS`. Existing projects keep working as before, but without per-token attempt counting (only the per-IP limit applies). To enable it, apply this migration: create a migration with `kronbase migration new add-otp-attempts`, paste the `ALTER` and run `kronbase migration apply <target>`:

```sql
ALTER TABLE AUTH_OTP_TOKENS ADD (ATTEMPTS NUMBER DEFAULT 0 NOT NULL);
```

If the column already exists, Oracle answers `ORA-01430`: `apply` stops and leaves the file pending, so mark it with `kronbase migration repair <target> --mark-applied <file>` (nothing changes in the database). The API detects the column per project and refreshes it about once a minute, with no restart.

> **Note:** The per-IP limit (10 verifications per minute) is not enough on its own: a 6-digit code could be tried from many IPs during its validity. The per-token counter limits guesses per code to `OTP_MAX_ATTEMPTS`.

> **Note:** Trade-offs:
> - Anyone who knows an email can burn the current code with `OTP_MAX_ATTEMPTS` wrong guesses (they could already cancel it by calling `otp/send`, which invalidates the previous token); the victim must request a new code.
> - A locked `combined` token also kills its magic link (it is the same row).
> - A new code resets the counter and there is no per-email limit, only per-IP limits (send 3/min, verify 10/min, `totp/verify` 10/min).
> - After applying the `ALTER` it can take up to ~1 minute to take effect (60 s detection cache); without the migration there is no per-token counting.
> - `OTP_MAX_ATTEMPTS` is a server environment variable: on Kronbase Cloud only the operator sets it; on BYOC/dedicated deployments you set it in your instance environment.

### Invitations and password reset

```typescript
await kb.auth().requestPasswordReset('user@example.com')
await kb.auth().confirmPasswordReset(token, 'N3w!password')

// Server only, service_role key
await admin.auth().inviteUser(userId, 'user@example.com')
```

| Endpoint | Body | Notes |
|---|---|---|
| `POST /api/auth/password-reset/request` | `{ email }` | Always answers `success: true` with the message `Si el email existe, recibirás un correo`. As with `otp/send`, the response goes out before the email is sent. |
| `POST /api/auth/password-reset/confirm` | `{ token, password }` | `400` with `PASSWORD_RESET_CONFIRM_ERROR` if the token is invalid, expired or already used. The token is single-use even if it is confirmed twice at the same time: only one confirmation changes the password and the other answers that the token was already used. Once it changes, the user's other pending reset links stop working. |
| `POST /api/auth/invite` | `{ userId, email }` | Requires a `service_role` key (`403` `FORBIDDEN` otherwise). |

Default lifetimes: invitation 72 hours, reset 24 hours. The emails carry a link of the form `<base_url>?token=<token>&type=<type>` with `type` of `invite`, `recovery` or `magiclink`; see the Auth section.

### Two-factor authentication (TOTP)

Users enrol a TOTP authenticator through endpoints that require both `x-api-key` and the user's Bearer token.

```typescript
const { qrUri, secret } = await kb.auth().totp.setup()
const { backupCodes } = await kb.auth().totp.verifySetup('123456')
await kb.auth().totp.regenerateBackupCodes('123456')
await kb.auth().totp.disable('123456')
```

These helpers need a client with a cookie adapter (they send the `access_token` cookie as Bearer). Without one, call the endpoints directly:

```bash
curl -X POST https://api.kronbase.dev/api/auth/totp/setup \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>" \
  -H "Content-Type: application/json" -d '{}'
```

The `totp/setup`, `verify-setup`, `disable` and `backup/regenerate` endpoints answer `401` with `UNAUTHORIZED` when the Bearer token is missing or invalid.

Each authenticator code works only once: after using it (to confirm the setup, sign in, disable or regenerate the backup codes) wait for the next code, which changes every 30 seconds. The same code repeated answers as an invalid code.

| Endpoint | Body | Response |
|---|---|---|
| `POST /api/auth/totp/setup` | none | `{ success, qrUri, secret }` |
| `POST /api/auth/totp/verify-setup` | `{ code }` | `{ success, backupCodes }` (8 codes, shown once) |
| `POST /api/auth/totp/disable` | `{ code }` | `{ success }` |
| `POST /api/auth/totp/backup/regenerate` | `{ code }` | `{ success, backupCodes }` |

Once TOTP is enabled, `signin` no longer returns a session after a correct password. It returns an intermediate token valid for 5 minutes:

```json
{
  "success": true,
  "requires2FA": true,
  "sessionToken": "eyJ...",
  "availableMethods": ["totp", "email"]
}
```

Complete the second factor with `POST /api/auth/totp/verify`. `method` is `totp` (an authenticator code or one of the backup codes, each usable once, also when two requests arrive at the same time) or `email` (a code sent by `sendOtp`; it needs email enabled, otherwise `503` `EMAIL_NOT_CONFIGURED`).

```bash
curl -X POST https://api.kronbase.dev/api/auth/totp/verify \
  -H "x-api-key: $KB_ANON_KEY" -H "Content-Type: application/json" \
  -d '{ "sessionToken": "<sessionToken>", "code": "123456", "method": "totp" }'
```

The response has the same shape as `signin`. An invalid or expired `sessionToken` returns `401` with `INVALID_SESSION_TOKEN`, and a wrong code with `method: "totp"` returns `401` with `INVALID_TOTP_CODE`. With `method: "email"` an invalid, used or expired code returns `401` with `TWO_FA_VERIFY_ERROR`.

```typescript
// With the SDK: totp.verify takes the sessionToken from the signin response
const result = await kb.auth().totp.verify(sessionToken, '123456', 'totp')
```

> **Note:** `kb.auth().signIn()` does not return the `sessionToken`: when the account has 2FA it returns `{ success: false, error: 'Invalid response from server' }`. To sign in accounts with TOTP, call `POST /api/auth/signin` directly to read `sessionToken`, then use `totp.verify`.

### Sign-in providers

Each project enables its own sign-in providers: **Microsoft, Google, Apple, GitHub** and **generic OIDC** (any OpenID Connect server: Oracle IDCS/OCI IAM, Okta, Auth0, Keycloak…). Configuration is per project (dashboard, CLI or admin API); there are no provider environment variables. End-user accounts remain your project's accounts: signing in with a provider ends in the same session (access and refresh JWT) as `signin`.

#### Supported providers

Each provider is identified by a **slug**. For Microsoft, Google, Apple and GitHub the slug is the provider name and there is only one per project. With OIDC you can have several, each with its own slug (lowercase letters, digits and hyphens, up to 63 characters, starting with a letter; `microsoft`, `google`, `apple`, `github`, `exchange`, `token` and `callback` are reserved).

| Provider (`provider`) | What it needs | Mobile flow (ID token) |
|---|---|---|
| `microsoft` | Client ID, client secret and `tenant` (`common`, `organizations`, `consumers`, a GUID or a verified domain); optional `trustTenantEmail` (see "Trusting the tenant's email") | Yes; nonce is optional |
| `google` | Client ID, client secret and, for mobile apps, the extra audiences (`audiences`: the iOS/Android client IDs) | Yes; nonce required |
| `apple` | Services ID (the client ID), `teamId`, `keyId` and the `.p8` private key as the secret; optional `audiences` (iOS bundle ids) | Yes; nonce required (plain or SHA-256) |
| `github` | Client ID and client secret | No: GitHub does not issue ID tokens |
| `oidc` | `issuer` (https), client ID, client secret and optionally `scopes` (must include `openid`; default `openid email profile`) and `audiences` | Yes; nonce required |

With OIDC, Kronbase reads the issuer's configuration (`/.well-known/openid-configuration`) when you save the provider; if it cannot be read, saving fails with `OIDC_DISCOVERY_FAILED`.

#### Before enabling a provider

1. **Site URL.** Required to enable any provider **that uses the public callback** (all except those with an own redirect URI: see "Private flow (server to server)"). It is the URL of your app the browser returns to, both on success (with `?code=`) and on error (with `?error=`). It must be absolute, `https` (or `http` only for `localhost`), with no credentials and no fragment (`#`). It cannot be removed while providers that use the public callback are enabled.
2. **Callback URL.** Each provider has its own callback URL, which you must register **exactly as shown** in the provider's console (Azure/Entra, Google Cloud, Apple Developer, GitHub or your OIDC server). The dashboard, the CLI and the admin API show it already built; the format is:

   ```text
   https://<your-api>/api/auth/oauth/<projectId>/<slug>/callback
   ```

   `<your-api>` is the public URL of the API (on Kronbase Cloud, the platform's; on a dedicated deployment, your deployment's: see `PUBLIC_API_URL` in [BYOC and dedicated deployment](/en/docs#byoc-dedicated)). Note: on a dedicated deployment the tunnel's default rule only exposes `^/platform/`, so that callback is **not** reachable from the internet unless you add an extra path rule; with a private API use the private flow. If the API has no public URL configured, no provider that uses the public callback can be enabled (`AUTH_PUBLIC_URL_MISSING`). With an own redirect URI (private flow) neither the site URL nor the API's public URL is needed.
3. **Allowed redirects (optional).** By default the browser returns to the site URL. To return to another URL (for example `/auth/callback` or a mobile app's custom scheme such as `myapp://auth`), add it to the provider's allowed redirects and pass it as `redirect_to` when starting. The match is **exact**, with no wildcards: it is normalized the same way as when saving and the stored value is used; if it matches no entry, the site URL is used. `https`, `http` only for `localhost`, or an app's own scheme are accepted (not `javascript:`, `data:`, `file:`, `vbscript:`, `blob:` or `about:`); up to 20 redirects.

#### Configure

- **Dashboard:** in the project, the **Proveedores de inicio de sesión** (sign-in providers) card. The secret is never shown again; only whether one is stored is indicated, and leaving it empty when editing keeps the stored one.
- **CLI:** `kronbase auth ...` (see [CLI](/en/docs#cli)).
- **Admin API** (used by the dashboard; only the project owner, or whoever holds the control key on a dedicated deployment):

| Method and route | What it does |
|---|---|
| `GET /platform/customers/me/projects/:id/auth/providers` | Lists the providers (with their `redirectUri` and `callbackUrl`), the site URL and whether the API has a public URL |
| `PUT /platform/customers/me/projects/:id/auth/providers/:slug` | Creates (`201`) or updates (`200`) a provider |
| `PATCH /platform/customers/me/projects/:id/auth/providers/:slug` | Enables or disables (`{ "enabled": true }`) |
| `DELETE /platform/customers/me/projects/:id/auth/providers/:slug` | Deletes the provider |
| `PUT /platform/customers/me/projects/:id/auth/site-url` | Sets the site URL (`{ "siteUrl": "https://app.com" }`) or removes it (`null`) |

The `PUT` carries `provider`, `clientId`, `clientSecret` (required when creating; absent or empty when updating keeps the stored one), `config` (the fields in the table above; always send it complete), `enabled`, `linkExistingByEmail` (default `false`), `allowSignup` (default `true`), `allowedEmailDomains` (up to 50), `allowedRedirects` (up to 20) and `redirectUri` (own redirect URI; `null` removes it, absent keeps the stored one). Responses also carry `redirectUri` and `callbackUrl` (`null` when there is an own URI). Responses never include the secret: only `hasSecret`. Own errors: `INVALID_PROVIDER_CONFIG` (`400`), `OIDC_DISCOVERY_FAILED` (`400`), `INVALID_SITE_URL` (`400`), `AUTH_SITE_URL_REQUIRED` (`409`, no site URL when enabling), `AUTH_PUBLIC_URL_MISSING` (`409`), `AUTH_SITE_URL_IN_USE` (`409`, when removing the site URL with enabled providers) and `NOT_FOUND` (`404`).

- **`config` is replaced as a whole.** Unlike the secret, whatever you leave out of `config` is removed: a `PUT` without `config` stores `{}` (for Google it drops its `audiences`; for Microsoft, Apple or OIDC, which have required fields, it answers `400`), and an Apple or OIDC `config` without `audiences` drops them. The dashboard and the CLI always send it complete; if you call the API directly, send the current `config` with your changes. To only enable or disable, use the `PATCH`.
- **An OIDC issuer cannot be changed.** A `PUT` that changes the `issuer` of an existing OIDC slug answers `400` (`INVALID_PROVIDER_CONFIG`): linked accounts are identified by slug and `subject`, so for another issuer create a new slug. The Microsoft `tenant` can be changed (see "Provider notes").

#### Browser flow

A browser cannot send the `x-api-key` header on a redirect, so the start is a call that returns the URL to navigate to. The SDK does all of this for you (see [Authentication](/en/docs#auth)); this is the REST contract:

1. **Start:** `GET /api/auth/oauth/:slug?code_challenge=<challenge>&redirect_to=<url>` with `x-api-key`. It returns `{ "success": true, "url": "<provider authorization url>" }`. The app navigates to that `url`. `code_challenge` is **required**: `base64url(sha256(code_verifier))` without padding (43 characters), with an optional `code_challenge_method=S256` (the only method); without it, `400` with `OAUTH_PKCE_REQUIRED`.
2. **Callback:** the provider sends the user back to Kronbase's callback URL (public, no API key; Apple arrives with a cross-site `POST` and Kronbase answers with a `GET` redirect). Kronbase validates the `state`, exchanges the code with the provider, resolves the account and redirects to your app with **`?code=<code>`**.
3. **Exchange:** `POST /api/auth/oauth/exchange` with `x-api-key` and the body `{ "code": "<code>", "code_verifier": "<verifier>" }`. It returns the session in the same shape as `signin`. The code expires after 120 seconds and is **single-use**, even if the exchange fails.

Tokens never travel in the return URL. **Why PKCE in the app:** only the app (or browser) that started the flow knows the `code_verifier`, so the `?code=` is only useful to whoever started it. This prevents someone from making you sign in to an account that is not yours (login CSRF) and prevents another app that registers the same custom scheme (`myapp://`) from intercepting the code and redeeming it. A missing, wrong or malformed verifier returns the same generic `400` `OAUTH_CODE_INVALID` as a non-existent or expired code, and spends the code.

If something fails in the callback, the browser returns to your app with `?error=<code>&error_description=<message>` and never with tokens. The redirect goes to the site URL when the `state` is not valid, and to the resolved destination (the allowed `redirect_to` or, otherwise, the site URL) for the rest of the errors. If the project or the provider do not exist or are disabled, or the project has no site URL, the callback answers `404` with a JSON body instead of redirecting.

```typescript
// When the browser returns to your app
const params = new URLSearchParams(window.location.search)
if (params.get('error')) {
  showError(params.get('error'), params.get('error_description'))
} else if (params.get('code')) {
  const result = await kb.auth().exchangeCodeForSession(params.get('code')!)
}
```

#### Mobile sign-in with an ID token

A native app that already got an ID token from the provider (Sign in with Apple, Google Sign-In, MSAL, an OIDC SDK…) redeems it directly: `POST /api/auth/oauth/:slug/token` with `x-api-key` and `{ "idToken": "...", "nonce": "..." }`. It returns the session in the shape of `signin`. No PKCE and no redirects.

- The token is verified against the provider's public keys: signature, algorithm, issuer, audience (the provider's client ID plus the configured `audiences`), expiry and `nonce`. If the token carries `azp` (the client that requested it), it must also be the client ID or one of the `audiences`.
- `nonce` is required for Google, Apple and OIDC (plain; Apple also accepts its SHA-256) and optional for Microsoft. The app must **generate a fresh nonce on every sign-in** and send the same one to the provider and to Kronbase.
- **Each ID token is accepted only once.** A retry with the same token gets the same generic `401` (`OAUTH_ID_TOKEN_INVALID`) as an invalid token; it is not revealed that it was already used.
- **The token is spent before the account is resolved.** If the response is an error after verification, for example `OAUTH_SCHEMA_PENDING` (`503`, retry), `OAUTH_ACCOUNT_EXISTS` or `OAUTH_SIGNUP_DISABLED`, that ID token is no longer usable: to retry, the app must get **a fresh ID token** (with a fresh nonce) from the provider.
- GitHub does not support this flow (`OAUTH_ID_TOKEN_UNSUPPORTED`).

#### Private flow (server to server)

**Why.** In the regular browser flow the provider (Microsoft, Google…) sends the user back to a public URL of the Kronbase API. A dedicated (BYOC) deployment usually keeps its API **private**, not exposed to the internet, so the provider cannot reach it. In the private flow the provider sends the user back to **a route of your own app** (the "own redirect URI") and **your app's backend** forwards `code` and `state` to Kronbase with the project API key. Only your backend needs to reach the API; the user's browser never talks to it.

**Step by step:**

1. **Configure the provider** with an own redirect URI (see "Configuring the own redirect URI" below) and register it exactly the same in the provider's console.
2. **Start (your backend):** `GET /api/auth/oauth/:slug?code_challenge=<challenge>` with `x-api-key`, like the browser flow; it returns `{ "success": true, "url": "<provider authorization URL>" }`. Your backend stores the PKCE `code_verifier` (the SDK does it for you) and redirects the user to that `url`. In this mode `redirect_to` is not used: where the user goes afterwards is up to your app.
3. **Return:** the provider redirects the browser to your redirect URI with `?code=<code>&state=<state>` (or `?error=...` if the user cancelled: see below).
4. **Complete (your backend):** `POST /api/auth/oauth/:slug/complete` with `x-api-key` and the body `{ "code": "<code>", "code_verifier": "<verifier>", "state": "<state>" }`. It answers `200` with `{ "success": true, "data": { "accessToken": "...", "refreshToken": "...", "expiresAt": "<ISO 8601>" } }` and `cache-control: no-store`. **The response has no `user`**, only the session tokens.
5. **Your app** stores its own session (cookies, etc.) with those tokens and redirects the user wherever it wants.

`code` is the **provider's** authorization code (not the 120-second code of the regular flow). The `state` is signed, bound to the project and the provider, expires after 10 minutes and is **single-use**: it is consumed atomically before talking to the provider, so **any later failure leaves it spent** and you must start again from the start call. It does not depend on cookies or on the IP.

With the SDK (`signInWithOAuth` with `navigate: false` and `completeOAuthSignIn`, SDK 2.21 or later) these are two routes of your backend; the complete Next.js example and the raw HTTP variant are in [Authentication](/en/docs#auth). Raw HTTP variant, without the SDK:

```bash
# 2. Start: the verifier is 43 to 128 PKCE characters (A-Z a-z 0-9 - . _ ~); the challenge is base64url(sha256(verifier))
curl -s "https://<your-api>/api/auth/oauth/microsoft?code_challenge=<challenge>&code_challenge_method=S256" \
  -H "x-api-key: $KB_API_KEY"
# → { "success": true, "url": "https://login.microsoftonline.com/..." }   (store the verifier; redirect the user to the url)

# 4. Complete, with the code and state that reached your redirect URI
curl -s -X POST "https://<your-api>/api/auth/oauth/microsoft/complete" \
  -H "x-api-key: $KB_API_KEY" -H "content-type: application/json" \
  -d '{ "code": "<code>", "state": "<state>", "code_verifier": "<verifier>" }'
# → { "success": true, "data": { "accessToken": "...", "refreshToken": "...", "expiresAt": "2026-11-23T20:00:00.000Z" } }
```

##### Configuring the own redirect URI

The field is `redirectUri` in the admin API, **"URI de retorno propia (opcional)"** (own redirect URI, optional) in the dashboard and `--redirect-uri <url>` in the CLI (`--clear-redirect-uri` removes it; with neither, the stored one is kept). In the API, `redirectUri: null` removes it and omitting it keeps the stored one.

- **It is stored normalized and you must register it exactly like that.** Kronbase stores the URL's normalized `href`: `https://app.com` is stored as `https://app.com/`. Register in the provider's console (Azure/Entra, Google Cloud, Apple Developer, GitHub…) **the value exactly as the dashboard, the CLI or the API returns it**, not the one you typed. That same value is used in the authorization and, identically, in the code exchange with the provider (the `state` stores it and the exchange never recomputes it); if it does not match exactly what is registered, the provider rejects the exchange and you get `OAUTH_PROVIDER_ERROR` (`502`).
- **Rules:** absolute `https` URL, no credentials or fragment (`#`), no spaces or wildcards, up to 2048 characters. `http` is accepted for `localhost`, `127.0.0.1` and `[::1]`, **meant for development**: use `https` in production. (An instance in local development mode, `LOCAL_DEV=true`, accepts `http` on any host.)
- **With an own redirect URI neither the site URL nor `PUBLIC_API_URL` is needed** to enable the provider, and the API's public callback is **not used**: the provider listing shows `callbackUrl: null` and `redirectUri`. A `state` issued in this mode that reaches the public callback fails with `OAUTH_STATE_INVALID`. If you remove the own URI from an enabled provider, it depends on the public callback again and the site URL and `PUBLIC_API_URL` are required again (`409` if missing).
- It works for every browser provider (Microsoft, Google, Apple, GitHub and OIDC). It does not change the mobile ID-token flow.

##### `complete` errors

Errors arrive as `{ "success": false, "error": "<message>", "code": "<code>" }`; messages are fixed and never carry provider text.

| Code | Status | When |
|---|---|---|
| `OAUTH_STATE_INVALID` | `400` | Any problem with the `state` **or with the verifier**: missing, tampered with, expired, already used, from another project or provider, issued by a public-callback flow, or the `code_verifier` is missing, malformed or does not match. It is always the same code and message, and the `state` is spent if it got consumed (a malformed verifier also spends it: it is checked after consuming it) |
| `QUERY_ERROR` | `400` | The body fails validation before anything else: `code` or `state` is empty or too long (`code` over 4096 characters, `state` over 1024). Nothing is consumed: the `state` is **not** spent |
| `OAUTH_PROVIDER_NOT_FOUND` | `404` | The provider does not exist, is disabled, or the project is not active (does not spend the `state`) |
| `OAUTH_PROVIDER_ERROR` | `502` | The provider failed or answered something unexpected when exchanging the code (for example a redirect URI that does not match the registered one) |
| `OAUTH_ID_TOKEN_INVALID` | `401` | The ID token the provider returned failed verification |
| `OAUTH_EMAIL_MISSING` | `400` | The profile has no usable email |
| `OAUTH_EMAIL_UNVERIFIED`, `OAUTH_EMAIL_DOMAIN_NOT_ALLOWED` | `403` | Allowed-domains list: unverified email or domain not allowed |
| `OAUTH_ACCOUNT_EXISTS` | `409` | An account with that email already exists and the linking rules do not allow linking it |
| `OAUTH_SIGNUP_DISABLED` | `403` | There is no account and the provider has sign-ups disabled. Your app can map it to its own message (for example "User not found in the system") |
| `OAUTH_ACCOUNT_DISABLED` | `401` | The account exists but is disabled |
| `OAUTH_SCHEMA_PENDING` | `503` | The project is being updated; the `state` is already spent: restart the sign-in |
| `RATE_LIMITED` | `429` | Too many attempts; wait a minute |
| `OAUTH_COMPLETE_ERROR` | `500` | Unexpected server error |

Also, a missing or invalid API key answers `401`, and a body without `code` or without `state` answers a `400` validation error. The other codes in "Response codes" (`OAUTH_CODE_INVALID`, `OAUTH_PKCE_REQUIRED`, `OAUTH_PROVIDER_DENIED`…) are not returned by `complete`.

If the user cancels at the provider, it redirects to your redirect URI with `?error=...&error_description=...` (provider text: do not show it as is): your route handles it and does **not** call `complete`; that `state` simply expires.

##### Private-flow rate limits

Per minute: start allows 120 per IP and project and 600 per project; `complete`, 120 per IP and project and 300 per project. Since all traffic in this flow comes from your backend's IP, the project limit is the one that matters. On a private dedicated deployment, where only your backend reaches the API, you can raise every limit with `RATE_LIMIT_MULTIPLIER` (see [BYOC and dedicated deployment](/en/docs#byoc-dedicated)). The counter lives in each API process's memory: it resets on restart and is not shared between instances.

##### Limitations

- **Same browser (verifier in a cookie).** The SDK stores the `code_verifier` in an httpOnly cookie `kronbase_pkce_verifier` (`SameSite=Lax`, 10 minutes, `path=/`) on **your domain**, so the user must come back in the **same browser** that started the flow, and your redirect URI must be on the same host that wrote the cookie (it is a cookie with no `Domain` attribute). If you start and complete in different processes or devices, pass your own `pkceStorage` to the client, backed by your store (for example a database or a cache tied to your app's session). `createServerClient` from `@kronbase/ssr` does not forward `pkceStorage` (it only takes the cookies): to pass one, build the client with `createClient` from `@kronbase/client`, with your `pkceStorage` and, if you want session cookies, your own `cookieAdapter`.
- **Where the start runs, and one start at a time.** `signInWithOAuth` must run in a Route Handler, a Server Action or a middleware with a writable `cookieAdapter` (or with a per-request `pkceStorage`, which requires `createClient` from `@kronbase/client`; `createServerClient` from `@kronbase/ssr` does not forward it). In a Server Component cookie writes fail silently and the verifier is lost (`OAUTH_PKCE_MISSING` on complete). The SDK does not fall back to memory: without a `cookieAdapter` or `pkceStorage` it returns `OAUTH_PKCE_STORAGE`; `pkceStorage: 'memory'` is only for single-user scripts, never for a multi-user server. There is one verifier per browser: a second start invalidates the first. `completeOAuthSignIn` deletes the verifier after **any** attempt (also on a `429` or a network error) and the `state` is single-use, so any failure means restarting the sign-in.
- **`redirect_to`, allowed redirects and site URL.** With an own redirect URI they are ignored for that provider: your app decides where the user goes.
- **Apple.** Apple sends the user back with a **cross-site** form `POST` (`response_mode=form_post`): your redirect route must accept `POST`, and the browser **does not send** a `SameSite=Lax` cookie on a cross-site `POST`. So with the SDK's default cookie, `completeOAuthSignIn` does not find the verifier and returns `OAUTH_PKCE_MISSING` without calling the API (the `state` is not spent). What fits: your redirect route accepts the `POST`, reads `code` and `state` from the body and answers a `303` redirect to **a `GET` of your own route** with `code` and `state` in the query; that route calls `completeOAuthSignIn`, and the `Lax` cookie does travel on a top-level `GET` navigation. The other option is your own `pkceStorage` that the `POST` can read (it requires `createClient` from `@kronbase/client`; `createServerClient` from `@kronbase/ssr` does not forward it). Do not store the verifier on your server keyed only by the `state`, with no tie to the browser: you would lose what stops someone from making you complete **their** sign-in. We have not tested it end to end with a real Apple app or with every browser. Also, the user's **name**, which Apple sends only the first time in the form's `user` field, **does not reach** Kronbase in this flow: `complete` only receives `code`, `state` and `code_verifier`, so the account is created without a name.
- **Identity by slug and `subject`** (without the issuer), as in the other flows: see "Deleting a provider".

#### Response codes

Messages are fixed and never carry provider text. In the browser they arrive as `?error=<code>&error_description=<message>`; in REST calls, as `{ "success": false, "error": "<message>", "code": "<code>" }` with the HTTP status in the table.

| Code | Status | When |
|---|---|---|
| `OAUTH_PKCE_REQUIRED` | `400` | `code_challenge` is missing, not a valid S256, or `code_challenge_method` is not `S256` |
| `OAUTH_CODE_INVALID` | `400` | The exchange code does not exist, expired, was already used, belongs to another project, or the `code_verifier` does not match. Always the same message |
| `OAUTH_STATE_INVALID` | `400` | (In `complete`, also a missing or wrong `code_verifier`.) The callback `state` is missing, tampered with, expired (10 minutes), already used, or from another project or provider |
| `OAUTH_PROVIDER_DENIED` | `400` | The user canceled or the provider returned an error |
| `OAUTH_PROVIDER_ERROR` | `502` | The provider failed or answered something unexpected (network, code exchange, discovery) |
| `OAUTH_ID_TOKEN_INVALID` | `401` | The ID token failed verification or was already used |
| `OAUTH_ID_TOKEN_UNSUPPORTED` | `400` | The provider does not issue ID tokens (GitHub) |
| `OAUTH_NONCE_REQUIRED` | `400` | The provider requires `nonce` in the mobile flow and none was sent |
| `OAUTH_EMAIL_MISSING` | `400` | The provider profile has no usable email |
| `OAUTH_EMAIL_UNVERIFIED` | `403` | There is an allowed-domain list and the provider did not verify the email |
| `OAUTH_EMAIL_DOMAIN_NOT_ALLOWED` | `403` | The email's domain is not among the allowed domains |
| `OAUTH_ACCOUNT_EXISTS` | `409` | An account with that email already exists and the linking rules do not allow linking it; the user must use their usual method |
| `OAUTH_SIGNUP_DISABLED` | `403` | There is no account and the provider has sign-ups disabled |
| `OAUTH_ACCOUNT_DISABLED` | `401` | The account exists but is disabled |
| `OAUTH_PROVIDER_NOT_FOUND` | `404` | The provider does not exist, is disabled, or the project is not active |
| `AUTH_SITE_URL_REQUIRED` | `409` | The project has no site URL |
| `AUTH_PUBLIC_URL_MISSING` | `503` | The API has no public URL configured |
| `OAUTH_SCHEMA_PENDING` | `503` | The project is being updated; retry in a few seconds (in the mobile flow, with a fresh ID token) |
| `RATE_LIMITED` | `429` | Too many attempts; wait a minute |

#### Account linking, sign-ups and domains

A user's identity is the pair **provider (slug) + `subject`** from the provider; the email never identifies the person, it only serves to link or sign up. An already linked user enters their own account even if their email changed, unless that account is disabled (`OAUTH_ACCOUNT_DISABLED`). For a user with no linked identity, the decision order is:

1. **Allowed domains** (`allowedEmailDomains`, empty = any): if there is a list, the provider must have verified the email (`OAUTH_EMAIL_UNVERIFIED`) and its domain must be on it (`OAUTH_EMAIL_DOMAIN_NOT_ALLOWED`).
2. **An account with that email already exists.** It is linked if any of these rules holds; otherwise `OAUTH_ACCOUNT_EXISTS`:
   - The **Link by email** option (`linkExistingByEmail`) is on for the provider **and** the provider verified the email.
   - One-time linking of password-less accounts: the account has no password (a provider created it, like the old Microsoft sign-in), has no linked identity yet, and the provider verified the email. This rule applies even if "Link by email" is off. For **Microsoft**, an unverified email is also linked **only if the account was created by the old Microsoft flow** (the case for people who used Microsoft before this change) **and the configured `tenant` is a specific tenant** (a GUID or a verified domain). Not with `common`, `organizations` or `consumers`: any other tenant can put someone else's email in its profile, so a verified email (`xms_edov`) is required. It is a one-time link: afterwards the account enters through its identity.
   - Only after it is decided that linking is allowed is the account checked for being disabled (`OAUTH_ACCOUNT_DISABLED`); if it cannot be linked, the result is `OAUTH_ACCOUNT_EXISTS`.
3. **The account does not exist:** a new password-less account is created (`signin` rejects it) if the provider allows sign-ups (`allowSignup`); otherwise `OAUTH_SIGNUP_DISABLED`.

What «verified email» means depends on the provider:

| Provider | The email counts as verified when |
|---|---|
| Google | the ID token carries `email_verified: true` |
| Microsoft | the ID token carries the optional `xms_edov` claim with a true value (domain verification of the email), in any tenant; only the `email` claim, never `preferred_username`. With "Trust the tenant's email" (specific tenant), it is enough that the token carries `email` or a `preferred_username` with an email shape |
| Apple | the ID token carries `email_verified` |
| GitHub | the email is the user's verified primary address (or, failing that, the first verified one) |
| OIDC | the ID token carries `email_verified: true` |

Google, Apple and GitHub guarantee verification; Microsoft and generic OIDC providers **do not**: it depends on the tenant or the server. That is why the dashboard warns when you turn on "Link by email" for those providers. Turn on linking by email only if you trust that provider to verify emails.

**Scope of the rules.** `allowedEmailDomains` and `allowSignup` only govern **new** links and sign-ups: anyone already linked keeps entering even if their domain stops being allowed or sign-ups are closed. To revoke someone, disable their account.

**TOTP.** No sign-in with a provider asks for the project's TOTP (the provider handles the second factor), and no linking does either, including the one-time linking of password-less accounts.

#### Provider notes

- **Microsoft.** The `subject` is `tid:oid` (the user's tenant and object in the token) and does not change for a person. The email only counts as verified if the token carries the optional `xms_edov` claim (domain verification of the email); configure it in the app registration. It is needed in **any** tenant (a specific one too) if you want to link by email or use allowed domains: without it, with allowed domains every sign-in gets `OAUTH_EMAIL_UNVERIFIED`, and "Link by email" never links. **Alternative for your own company's tenant:** "Trust the tenant's email", which replaces this requirement (see "Trusting the tenant's email (Microsoft)"). Changing the configured `tenant` to another directory locks out the users of the previous one and admits those of the new one; switching to `common`, `organizations` or `consumers` admits users from any directory.
- **Google.** For mobile apps, add to `audiences` the iOS/Android client IDs whose ID tokens you will accept. Even if you request the ID token with the web client ID (`aud`), Google puts the Android or iOS client ID in `azp`: if it is not in `audiences`, the token is rejected.
- **Apple.** The `.p8` key must be PKCS#8 (`-----BEGIN PRIVATE KEY-----`) on the P-256 curve (ES256); Kronbase signs the client secret on every exchange. Apple's callback is a cross-site `POST` to the API, which redirects (`GET`) to your app. The user's name arrives only the **first** time they authorize your app. In the private flow the name does not reach Kronbase (see its limitations).
- **GitHub.** Requests the scopes `read:user user:email`. **GitHub Apps** (client ID starting with `Iv1.` or `Iv23`) ignore `scope`: give the app the "Email addresses" permission or sign-in fails. A regular OAuth App does not need it.
- **OIDC.** The `subject` is the issuer's `sub`. If you add `audiences`, the mobile ID token may come from other client IDs.

#### Trusting the tenant's email (Microsoft)

The **"Confiar en el correo del tenant"** (trust the tenant's email) option (`trustTenantEmail` in `config`; in the CLI, `--trust-tenant-email` / `--no-trust-tenant-email`) is Microsoft only.

**What it does.** When on, the address in the token counts as **verified**: the `email` claim and, if absent, `preferred_username` (the UPN) when it has an email shape. It **replaces** the requirement of the optional `xms_edov` claim. Without it, behavior is as usual (only `email` with `xms_edov`). The `subject` is still `tid:oid`.

**Only with a specific tenant.** It is only accepted if the `tenant` is a GUID or a verified domain of an organization. It is rejected when saving (`400`, `INVALID_PROVIDER_CONFIG`) with `common`, `organizations`, `consumers` and with the GUID of Microsoft's personal-accounts tenant (`9188040d-6c67-4c5b-b112-36a304b66dad`, equivalent to `consumers`). If a stored value stops meeting this (for example a domain that resolves to the personal-accounts tenant), it is ignored and normal behavior applies. In the dashboard the switch is only available with a specific tenant. If you change the tenant to **any other value**, from the dashboard or the CLI, the stored option is dropped (the CLI warns you; the dashboard turns the switch off and shows a notice), because the trust was for the previous tenant: turn it back on if it still applies. Through the API, a `config` that carries both a multi-tenant authority and the option is rejected.

**What it means for security, in plain words.** Turning it on means you **trust every administrator of that tenant**. The email in the token (the `mail` attribute, or the UPN) can be set by the tenant's or Exchange administrators and, for **B2B guests**, it can be an address from outside the tenant that the tenant has not verified. With a specific tenant the token's `tid` is pinned to that tenant, so no other directory can put whatever email it wants; but **your tenant's B2B guests are included**. A guest whose UPN is `alice_gmail.com#ext#@tenant.onmicrosoft.com` has a UPN under the tenant's own domain, but which value the token carries in `preferred_username` depends on the kind of guest: it can be the `#EXT#` UPN or the guest's home sign-in address (for example `alice@gmail.com`). Kronbase uses the `email` claim and, if there is none, `preferred_username` when it looks like an email; check with your own tenant what your guests' tokens carry. Recommended only for **your own company's tenant**, where you already trust whoever administers it; do not turn it on if the tenant is not yours or if you do not want to admit guests. To keep out guests with external addresses, combine it with `allowedEmailDomains` set to your company's own domain (see below).

**How it combines with the other rules.** Since the email counts as verified, the linking and allowed-domains rules in "Account linking, sign-ups and domains" work:

- **"Link by email"** (`linkExistingByEmail`; without it a verified email does not link already existing accounts with a password) links the Microsoft identity to the account that already has that email (with or without a password); afterwards the account signs in through its identity.
- **"Allow sign-ups"** (`allowSignup`) decides what happens with an email that has no account: on, it is created; off, `OAUTH_SIGNUP_DISABLED` (`403`).

**Example: a customer with preloaded users who sign in with their corporate email.** Specific tenant + "Trust the tenant's email" on + "Link by email" on + "Allow sign-ups" off. Users that already exist in your project with that email sign in (their identity is linked the first time); anyone not preloaded gets `OAUTH_SIGNUP_DISABLED` (`403`), which your app can map to its own message, for example "User not found in the system".

#### Rate limits

Per minute: start allows 120 per IP and project and 600 per project, the callback 30 per IP, the code exchange 20 per IP, the private flow's `complete` 120 per IP and project and 300 per project, and the mobile flow 10 per IP and 300 per project (multiplied by `RATE_LIMIT_MULTIPLIER` if you adjust it on your instance). The per-project limits are a trade-off: anyone holding your project's public anon key can exhaust them and leave your users without sign-in for a minute.

**With SSR, the per-IP limits are your server's.** If your app's server performs the start and the exchange (the cookie pattern with `@kronbase/ssr`: a server action or route handler), Kronbase sees that server's IP, not the browser's. The code exchange allows 20 per IP, so a single app server is capped at about 20 provider sign-ins per minute with the regular flow (start allows up to 120 per IP and project). The private flow does not use that exchange: `complete` allows 120 per IP and project. Plan for retries with backoff on `RATE_LIMITED` (`429`) in your app.

#### Deleting a provider

Deleting a provider **keeps** the users and their linked identities; they simply cannot sign in with it until you create it again with the same slug.

> **Known limitation:** identities are stored by slug and `subject`, without the issuer. That is why an existing OIDC issuer cannot be changed, but if you **delete** an OIDC provider and create the same slug again with another issuer, another person's identity with the same `subject` would enter the accounts linked to the previous one. Do not reuse a deleted slug for another identity provider: create a new slug. With Microsoft the `tid` is part of the `subject`, so changing the `tenant` carries no such risk.

#### Security

- The client secret (and Apple's `.p8` key) is encrypted at rest and **never** returned: responses only say whether one is stored.
- Only the project owner can manage providers (on a dedicated deployment, also whoever holds the control key).
- The `state` is signed, bound to the project and the provider, expires after 10 minutes and is single-use; the callback also uses PKCE with the provider when the provider supports it.
- Calls to the URLs of an OIDC issuer you configure (discovery, JWKS, token endpoint) go only over `https` and to port 443, only to public addresses (including IPv4 addresses inside NAT64 or 6to4), without following redirects, capped at 5 seconds and 1 MiB, and the connection is made to the address already checked (the name is not resolved again, which prevents DNS rebinding). An internal issuer or one on another port cannot be used (only exception: the local stack, see "Testing providers locally").

#### Testing providers locally

`kronbase start --dev-idp` adds a **test** OpenID Connect provider to the local stack (see [CLI](/en/docs#cli)). **Development only: do not use in production.** It asks for no password: its sign-in page lists the test users and you pick one.

| User (`preferred_username`) | `sub` | Email | `email_verified` |
|---|---|---|---|
| `alice` | `dev-alice` | `alice@example.com` | `true` |
| `bob` | `dev-bob` | `bob@example.com` | `false` |
| `carol` | `dev-carol` | (no email) | — |

**Fixed development** credentials (not secret; they only work for this test service): issuer `http://localhost:9400`, client ID `kronbase-dev-client`, client secret `kronbase-dev-secret`.

**Flow.**

1. `kronbase start --dev-idp`.
2. `kronbase auth site-url http://localhost:5173` (your app's URL).
3. Register the OIDC provider with slug `dev-idp` (`kronbase start` prints the exact command; see [CLI](/en/docs#cli)).
4. Sign in from your app as with any provider (see "Browser flow" or "Private flow"): the browser goes to `http://localhost:9400/authorize`, you pick a user and come back with the session. `alice` exercises email linking and allowed domains. `bob` (unverified email) only gets `OAUTH_EMAIL_UNVERIFIED` when the provider has allowed domains. With "Link by email" and an existing account with his email, he is not linked (`OAUTH_ACCOUNT_EXISTS`). With neither, he signs in as a new user. `carol` (no email) gets `OAUTH_EMAIL_MISSING`.

**What the service does.** Code flow with mandatory PKCE S256, `state` and `nonce`, `response_mode` `query` or `form_post`; exchange with `client_secret_basic` or `client_secret_post`; the code is single-use and expires after 60 seconds; RS256 ID token with `iss`, `aud`, `sub`, `iat`, `exp`, `nonce`, `email`, `email_verified`, `name` and `preferred_username`. It accepts any `http://localhost` (any port) as `redirect_uri`; other origins with `DEV_IDP_REDIRECT_ORIGINS` in `.kronbase/.env`.

**Your own users.** `.kronbase/dev-idp-users.json`, a JSON list of objects with `sub` and `preferred_username` (required and unique) and, optionally, `name`, `email` and `email_verified` (only together with `email`). Any other field stops the service from starting, and so does the file not being readable by uid 1000 (the container's `node` user; for example, mode `644`).

**Limits.**

- Local stack only: the API accepts an `http://localhost` issuer (any port) **only** with `LOCAL_DEV=true`, which only `kronbase start` uses. Kronbase Cloud and BYOC still require `https` and a public address (see "Security").
- Inside the network shared with the API container it listens on all interfaces, so other containers of the stack can reach it; outside, it is published only on `127.0.0.1`. Acceptable because it is development-only.
- There is no Microsoft-compatible mode: the `microsoft` provider always talks to `login.microsoftonline.com`, so it cannot be tested against the test service. Testing the Microsoft flow needs a real Entra tenant.
- The signing key is generated on each start of the service; no `userinfo` or provider refresh tokens (Kronbase does not use them).

#### Migrating from environment-variable configuration

Sign-in with Microsoft used to be configured with API process variables. They are no longer read: `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, `MICROSOFT_TENANT_ID`, `MICROSOFT_CALLBACK_URL`, `OAUTH_SUCCESS_REDIRECT_URL` and `OAUTH_STATE_SECRET`. The same goes for any you had set by hand on a dedicated deployment's container.

Per-project configuration (dashboard, CLI and admin API) only exists in the new API, and the new API no longer reads those variables. The migration is therefore a **coordinated window**: **Microsoft sign-in stops working from the moment the API is updated until the project is configured and your app is updated.** Prepare everything you can beforehand to keep that window short.

**Before updating** (does not need the new API):

1. Register the **new callback URL** in the Azure/Entra app registration, keeping the old one during the transition. It is known in advance: `https://<your-api>/api/auth/oauth/<projectId>/microsoft/callback`.
2. Decide whether you will turn on "Link by email". If your users already have passwords (for example a single-tenant app where the old flow linked any existing account by email), you will need it, plus the optional `xms_edov` claim in the app registration: configure that now. Without both, those users get `OAUTH_ACCOUNT_EXISTS` (`409`).
3. Prepare your app's change to the `?code=` contract with PKCE, with `@kronbase/client` 2.21 or later: `signInWithOAuth('microsoft')` and `exchangeCodeForSession(code)` instead of reading `access_token` and `refresh_token` from the URL (the redirect no longer carries tokens). Have it ready to ship the same day.

**After the API is updated** (the outage starts here):

4. On a dedicated deployment, set `PUBLIC_API_URL` in the "Ajustes del API" (API settings) card (see [BYOC and dedicated deployment](/en/docs#byoc-dedicated)). The tunnel's default rule does not expose the callback: add the optional path rule described there (knowing it exposes that route) or, better, use the private flow. It needs the new updater and recreates the API container (about 10 to 15 seconds).
5. In your project, set the **site URL** (what used to be the success URL) and configure the Microsoft provider (client ID, secret and tenant; your tenant's GUID is better than `common`), with "Link by email" if you decided on it in step 2.
6. Ship the version of your app from step 3.

**If your API is private** (a dedicated deployment not exposed to the internet), use the private flow: an own redirect URI on the provider and `completeOAuthSignIn` in your backend (see "Private flow (server to server)"). In that case you do not need `PUBLIC_API_URL` (step 4) or the site URL (step 5), and you register the own redirect URI in Entra instead of the callback URL from step 1. If your users are already loaded and sign in with their corporate email, see "Trusting the tenant's email (Microsoft)".

Only accounts that are **password-less and have no prior identity**, created by the old flow, link themselves on their first sign-in with the new provider, and only with a specific tenant (GUID or domain), following the one-time linking rule above. Accounts with a password do not link themselves: they need "Link by email" and `xms_edov` (step 2).

### Permissions (RBAC)

Roles and permissions are not embedded in the JWT. The token only identifies the user (`sub`); permissions are resolved on demand.

```typescript
const perms = await kb.auth().getPermissions()
// { authUserId, roles: [{ id, code }], permissions: ['orders.read', ...] } | null

if (perms?.permissions.includes('orders.approve')) {
  // show the approve button
}
```

```bash
curl https://api.kronbase.dev/api/auth/permissions \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>"
```

```json
{
  "success": true,
  "data": {
    "authUserId": "...",
    "roles": [{ "id": 1, "code": "manager" }],
    "permissions": ["orders.read", "orders.approve"]
  }
}
```

`permissions` is the union of the permissions of the user's roles and the permissions granted directly to the user, minus the permissions denied to that user. `getPermissions()` reads the `access_token` cookie, so it needs a cookie adapter, and returns `null` when there is no session or the request fails. The raw endpoint returns `401` with `UNAUTHORIZED` for an invalid token, and `400` with `QUERY_ERROR` when the `Authorization` or `x-api-key` header is missing. Roles and per-user permissions are managed with a `service_role` key through `POST /api/admin/users/:id/roles` (body `{ roleId }`) and `POST /api/admin/users/:id/permissions`.

#### Permission categories

`AUTH_PERMISSIONS` has an optional `CATEGORY` column (`VARCHAR2(100)`, nullable, free text) to group permissions in an admin UI. `GET /api/admin/users/:id/permissions` (`service_role` key) returns, for each permission, `module` (the `CODE` prefix before the first `.`, kept for backward compatibility) and `category`, which is the `CATEGORY` value if set, otherwise the `CODE` prefix, otherwise `null`. `CATEGORY` is not required: if you leave it empty, grouping falls back to the prefix of `CODE` (`overtime.approve_tec` is grouped under `overtime`).

Set it with your own SQL, for example through `/api/query` with a `service_role` key or from your seed scripts:

```sql
UPDATE AUTH_PERMISSIONS SET CATEGORY = 'Overtime' WHERE CODE LIKE 'overtime.%';
```

New projects are created with the column.

**Existing projects.** The `CATEGORY` column arrives on its own in projects created before this change: you do not have to apply any migration (see [Your project's platform schema keeps itself up to date](#your-projects-platform-schema-keeps-itself-up-to-date)). The migration only adds the empty column; it does not migrate or fill any data: fill `CATEGORY` yourself with `UPDATE` statements. While the column does not exist in a project yet (for example right after an update, before its first use), `category` is derived from the `CODE` prefix.

> **Note:** If you already added the column by hand with a migration of your own, nothing breaks: the platform detects it, does not create it again and marks it as applied.

> **Note:** The Data API does not evaluate permissions on `/query`: there it enforces the key type, the user's JWT and the project's RLS policies, which are scoped to the user ID from the token. The only exception is the `rls.bypass` mark (below). Permissions are evaluated in bucket policies: a policy can require a permission code to upload, delete or read files with the user's token (see "Uploading and deleting with the user session" in [Storage](/en/docs#storage)), and in RLS rules with `current_user_has_permission('code')` (see "Permission-based rules" in [Database](/en/docs#database)). Outside that they are informational for your application.

#### Service users: the `rls.bypass` mark

A background process (reports, exports, an email queue) that signs in as a regular user only sees its own rows once you enable RLS. To let it see every row without giving it the `service_role` key, mark that user with `rls.bypass`:

```bash
# Grant (creates the rls.bypass permission if it does not exist)
curl -X PUT https://api.kronbase.dev/api/admin/users/<userId>/rls-bypass \
  -H "x-api-key: $KB_SERVICE_ROLE_KEY"
# → { "success": true, "data": { "userId": "...", "rlsBypass": true } }

# Revoke
curl -X DELETE https://api.kronbase.dev/api/admin/users/<userId>/rls-bypass \
  -H "x-api-key: $KB_SERVICE_ROLE_KEY"
# → { "success": true, "data": { "userId": "...", "rlsBypass": false } }
```

The process does not change: it keeps signing in with its email and password and calling the API with the `anon` key and its JWT.

What the mark does:

- The user's requests to `/api/query` (including procedures and functions) and `/api/transaction` are not filtered by RLS: it reads, changes and deletes any user's rows in tables with RLS.
- Nothing else. The user still cannot use the `/api/admin/*` routes, the `AUTH_…` tables, external sources or any other operation that requires `service_role`, and it can only call procedures of the project's schema, like any user.
- It does not apply to realtime, notifications, storage or the routes for the user's own account: there it behaves like any user.

Rules:

- It can only be granted with a `service_role` key: with this endpoint, with `POST /api/admin/users/:id/permissions` (with the ID of the `rls.bypass` permission), or by writing to the permission tables yourself (for example, an `INSERT` into `AUTH_USER_PERMISSIONS` via `/api/query` with the `service_role` key). A user with their JWT cannot grant it to themselves or to others: the permission tables are admin-only.
- This endpoint refuses to mark an inactive user (`400` with `USER_INACTIVE`): reactivate them first. Revoking the mark of an inactive user is allowed.
- Only a **direct** grant to the user counts. A role that includes `rls.bypass` marks no one, so a default role or a broad role never grants bypass by accident.
- The mark is not inside the JWT: the server checks it on every request. Revoking it, or deactivating the user, takes effect within 30 seconds at most; with these endpoints, usually from the next request. The same applies if you change the permission tables with your own SQL (there it can always take up to 30 seconds). The user does not need to sign in again, either way.
- Deactivating a marked user does not remove the mark: if you reactivate them, they have bypass again. Revoke the mark if it is no longer needed.
- Up to 1000 marked users per project are taken into account. If there are more, the ones beyond that (in user ID order) get no bypass and the server logs a warning.
- Signing out does not invalidate an access token that was already issued: a stolen token of the process keeps bypass until you revoke the mark or the token expires (1 hour at most). Revoking the mark is how you cut it off immediately.
- Authentication audit log: this endpoint and `POST`/`DELETE /api/admin/users/:id/permissions` write `RLS_BYPASS_GRANT` or `RLS_BYPASS_REVOKE` when the permission is `rls.bypass`, and every sign-in or refresh of a marked user is logged with `metadata.rlsBypass = true`. Changes you make to the permission tables with your own SQL (for example, via `/api/query`) and reactivating a user who was already marked leave no grant or revoke entry; for those cases only the per sign-in or refresh entry remains.

> **Warning:** A marked user sees and changes the data of all your users in tables with RLS. Use it only for service accounts whose credentials you control, never for people. Keep in mind too that your project's procedures and functions run with the schema owner's rights and can write to the `AUTH_…` tables: if one of them changes permissions using data it receives from the user, it could be used to grant the mark.


### Your project's platform schema keeps itself up to date

Every project has the platform tables (`AUTH_*`) in its Oracle schema, plus some privileges the platform grants to the schema user. When a new version needs a change there (a column, a privilege), **the platform applies it on its own** to existing projects; you do not have to run or confirm anything.

**When it is applied.**

- **On first use.** The first time the project is opened after the new version is deployed, pending changes are applied before the request is served, with a wait cap of a few seconds: if they take longer, the request goes on with the current schema and the change finishes in the background.
- **In the background.** A slow, bounded sweep walks the projects nobody has opened, so they receive the changes too.

A new project is born up to date. If two requests or two instances open the same project at once, a lock makes only one of them apply the changes.

**The compatibility rule.** Changes are **additive and backward compatible only**: platform columns, privileges or tables are added; nothing is ever dropped or renamed, and your tables, views and data are never touched. The previous API version keeps working with the new schema (a BYOC updater rollback does not revert the database), and the new version tolerates a change that has not reached a project yet. Every change is idempotent: if the object already exists, it counts as applied.

**What you see.** The platform keeps a trace of what was applied in an internal table of the project's schema, `KRONBASE_SCHEMA_MIGRATIONS`, which does not show up in the dashboard explorer or in the schema endpoint, and is admin-only in the query builder. Because it lives in your own schema, your project's `service_role` key and `/execute` can read it (and modify it; don't: it is the trace the platform uses to know what it has already applied). In the project's **Overview** tab, the **Novedades** section (what's new; the dashboard shows it in Spanish) tells you, worded as features rather than schema changes, the platform features whose announcement date falls in the last 60 days, each with its state (applied, pending or failed): for example "Group your permissions by category" or "Create views in your project". It is informational, with no buttons. The list is also available at `GET /platform/customers/me/projects/:id/schema-features` (with `?lang=es|en`), one object per change: `since`, `title`, `description`, `applied`, `appliedAt` (only when applied) and `failed`.

**If a change fails.** A failure in one project does not affect the others, nor the project's ability to keep working as before. The platform retries on its own (about every 15 minutes) and notifies the deployment administrators. If **Novedades** shows a notice that a change could not be applied, you do not have to do anything: contact support with the project and the time; they can see the reason in the trace.

**Creating views.** One of the changes is the `CREATE VIEW` privilege for the schema user, needed for `kronbase migration` to create views. It is granted on its own; until then, `CREATE VIEW` fails with `ORA-01031`.

**Columns added by the platform.** If your SQL inserts positionally into `AUTH_*` tables (`INSERT INTO AUTH_PERMISSIONS VALUES (...)`), a new column breaks it: always list the columns.

> **Note (operators):** `TENANT_MIGRATIONS_ENABLED=false` (or `0`) turns the migrations and the sweep off; the other variables that tune them are in [BYOC and dedicated deployment](/en/docs#byoc-dedicated). On an existing self-managed installation, the platform administrator user needs, once, `GRANT CREATE VIEW TO <administrator user> WITH ADMIN OPTION` to be able to grant that privilege to projects; BYOC and `kronbase start` already have it. Until it is run, that change stays failed in each project without affecting the others.


---

# Transactions


## Transactions

`POST /api/transaction` runs several operations in a single Oracle transaction. The operations run one after another on the same connection; if all succeed the server does a `COMMIT`, and if any fails it does a `ROLLBACK` and none of the changes persist.

### Request

The body is `{ "operations": [...] }`. Each element has the same shape as the body of `POST /api/query` (`table`, `operation`, `data`, `rows`, `filters`, `returning`, and so on).

| Field | Rule |
|---|---|
| `operations` | Required array, between 1 and 100 elements. Outside that range the response is `400` with code `QUERY_ERROR`. |
| `operations[].operation` | `SELECT`, `INSERT`, `UPSERT`, `UPDATE`, `DELETE`, `PROCEDURE` or `FUNCTION`. |

Authentication is the same as for queries: `x-api-key` always, plus `Authorization: Bearer <accessToken>` when the key is `anon`. Unlike `/query`, with an `anon` key a transaction always requires the token, even if all the tables are public (`401`, `AUTH_REQUIRED`). A `service_role` key needs no token. See the Auth model section.

Each operation is validated before the transaction opens, with the same rules as `/query` (name format, `AUTH_TABLE_RESTRICTED` tables, `rows` between 1 and 1000, `limit` below the server maximum). A violation returns `403` with the validation code and nothing is executed.

> **Note:** Table restrictions (`AUTH_TABLE_RESTRICTED`) are checked on the main table of each operation and on every table in its `joins`. If any operation references a table that is not allowed, the transaction is rejected without running any operation.

```bash
curl -X POST https://api.kronbase.dev/api/transaction \
  -H "x-api-key: $KB_SERVICE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "operations": [
      { "table": "USUARIO", "operation": "INSERT",
        "data": { "NOMBRE": "John", "CORREO": "john@example.com" },
        "returning": ["ID"] },
      { "table": "AUDIT_LOG", "operation": "INSERT",
        "data": { "ACTION": "USER_CREATED", "USER_ID": { "$ref": { "op": 0, "column": "ID" } } } }
    ]
  }'
```

### With the SDK

`kb.transaction(operations)` takes the requests built with `.build()` on each builder and returns the response body as is. It does not throw when the transaction fails: check `result.success`.

```typescript
import { createClient, ref } from '@kronbase/client'

const kb = createClient('https://api.kronbase.dev/api', {
  serviceKey: process.env.KB_SERVICE_KEY!,
})

const result = await kb.transaction([
  kb.from('USUARIO')
    .insert({ NOMBRE: 'John', CORREO: 'john@example.com' })
    .returning(['ID'])
    .build(),
  kb.from('AUDIT_LOG')
    .insert({ ACTION: 'USER_CREATED', USER_ID: ref(0, 'ID') })
    .build(),
])

if (result.success) {
  console.log(result.results)        // one QueryResponse per operation, in order
} else {
  console.log(result.failedAt, result.code, result.error)
}
```

### Response

Success, status `200`:

```json
{
  "success": true,
  "results": [
    { "success": true, "data": { "ID": 42 }, "meta": { "affectedRows": 1 } },
    { "success": true, "data": { "ACTION": "USER_CREATED", "USER_ID": 42 }, "meta": { "affectedRows": 1 } }
  ]
}
```

`results[i]` corresponds to `operations[i]`. What each `data` contains depends on the operation:

| Operation | `results[i].data` |
|---|---|
| `SELECT` | Array of rows. `meta` has `limit`, `offset` and `total` (the number of rows returned). |
| `INSERT` with `returning` | Object with the returned columns. |
| `INSERT` without `returning` | The `data` you sent. |
| `INSERT` / `UPSERT` with `rows` | The `rows` you sent. `meta.affectedRows` has the count. |
| `UPDATE`, `DELETE` | `{ "affectedRows": n }` |
| `PROCEDURE` | `{}`, and the output in `results[i].plsql` (`outParameters`, `cursor`). |
| `FUNCTION` | The return value, also in `results[i].plsql.returnValue`. |

Failure, status `400`:

```json
{
  "success": false,
  "results": [ { "success": true, "data": { "ID": 42 }, "meta": { "affectedRows": 1 } } ],
  "error": "Operation failed",
  "code": "TRANSACTION_FAILED",
  "failedAt": 1
}
```

`results` holds only the operations that completed before the failure; they have already been rolled back along with the rest. `failedAt` is the index of the operation that failed.

| `code` | When |
|---|---|
| `TRANSACTION_FAILED` | An operation failed while executing; `failedAt` points to it. A database error inside an operation also arrives with this code; `error` carries a generic message (the detail stays in the server logs), except for your own error raised with `RAISE_APPLICATION_ERROR` (`ORA-20000` to `ORA-20999`), whose text alone is returned. |
| `PLSQL_ROUTINE_NOT_FOUND` | A `PROCEDURE`/`FUNCTION` operation called a routine that does not exist; `failedAt` points to it. |
| `INVALID_REF` | A `$ref` is malformed or points to something invalid. Nothing was executed (`failedAt: 0`). |
| `RLS_VIOLATION` | An `INSERT` or `UPDATE` would leave the row outside the user's RLS scope (HTTP `403` when it comes from a direct query; inside a transaction it arrives in the `400` body). |
| `TRANSACTION_ERROR` | Unexpected error; everything is rolled back. |
| `QUERY_ERROR` | The body does not match the schema (for example, 0 or more than 100 operations). |
| `DB_ERROR` | Database error raised outside the execution of an individual operation; the detail is only in the server logs. |
| `DB_POOL_EXHAUSTED` | `503`, temporarily out of connections; the response carries `Retry-After: 5`. |

### Returning and refs between operations

To use a value generated by the database (an identity or sequence ID, for example) in a later operation of the same transaction, ask for it with `returning` on an `INSERT` and refer to it with `{ "$ref": { "op": <index>, "column": "<COLUMN>" } }`. In the SDK, `ref(op, 'COLUMN')` produces that object.

```typescript
const result = await kb.transaction([
  kb.from('PEDIDO').insert({ CLIENTE: 'Ana' }).returning(['ID']).build(),
  kb.from('PEDIDO_ITEM')
    .insertMany(items.map((i) => ({ ...i, PEDIDO_ID: ref(0, 'ID') })))
    .build(),
  kb.from('PEDIDO').update({ ESTADO: 'CREADO' }).eq('ID', ref(0, 'ID')).build(),
])
```

Rules, validated before the transaction opens:

- A `$ref` can go in the values of `data`, in the values of each row of `rows`, and in the `value` of any filter (including nested filter groups).
- `op` must be the index of an **earlier** operation (`0 <= op < i`). A forward or self reference is rejected.
- The target operation must be an `INSERT` (not `UPSERT`) and its `returning` must include `column` (compared case-insensitively).
- The value is substituted before the SQL is built and always travels as a bind variable, never concatenated.
- An object with a `$ref` key that is not exactly `{ $ref: { op: number, column: string } }` returns `INVALID_REF`.
- If the target operation returns no value for the column, the transaction fails with `TRANSACTION_FAILED` at the operation that uses it.

`returning` is declared with `.returning(['COL', ...])` on `insert()`. It cannot be combined with `insertMany()` or `upsert()` (see the table below). The server reads the type of each column to return it: `NUMBER` as number, character columns (including UUIDs in `VARCHAR2`) as string, `DATE` and `TIMESTAMP` as date, and `RAW` as uppercase hex. Without information about the column it falls back to `NUMBER`.

| Combination | Result |
|---|---|
| `rows` with `data` or `returning` | `403`, `INVALID_ROWS` |
| `UPSERT` with `returning` | `403`, `INVALID_UPSERT` |
| `rows` with more than 1000 or 0 rows, or different columns per row | `403`, `INVALID_ROWS` |

### Locking: SELECT FOR UPDATE

`.forUpdate()` on a `select()` locks the rows until the transaction ends. It is only accepted inside a transaction; outside one, `/query` rejects it with `FOR_UPDATE_REQUIRES_TRANSACTION`. It can only be used with `SELECT` (`INVALID_FOR_UPDATE_OPERATION`).

```typescript
const result = await kb.transaction([
  kb.from('CUENTA').select(['ID', 'SALDO']).eq('ID', 7).forUpdate().build(),
  kb.from('CUENTA').update({ SALDO: 900 }).eq('ID', 7).build(),
])
```

`SELECT` operations in a transaction accept expressions (`fn`, `col`, `lit`, `cond`; see "Expressions in SELECT" in the database documentation), also with `.forUpdate()`. Each operation is validated separately and `$ref` cannot be used inside expression literals (`INVALID_EXPRESSION`). Against an older API without support, `transaction()` returns `code: 'EXPRESSIONS_UNSUPPORTED'` without sending anything; if the response to a `SELECT` with expressions still lacks `meta.expressions`, it returns the same code after running it, with `failedAt` pointing to that `SELECT`.

### PL/SQL inside a transaction

`PROCEDURE` and `FUNCTION` operations run in the same transaction and are rolled back with it. See the PL/SQL section for their parameters and for which routines can be called: if any cannot, the transaction is rejected with `403` and `INVALID_PLSQL_NAME` before any operation runs.

```typescript
kb.from('').procedure('PKG_USER.CREATE_USER', [
  { name: 'p_username', value: 'john', direction: 'IN' },
]).build()
```

> **Note:** Row-level security applies per operation using the user of the token (or no restriction for `service_role`). If an operation of the transaction violates a policy, the whole transaction is rolled back.

> **Note:** The response of a failed transaction has HTTP status `400`, but the SDK does not throw: it returns the body so that you can read `failedAt` and `code`.


---

# Mobile SDKs


## Mobile clients

Native apps and Flutter can use Kronbase without the JavaScript SDK: the data API publishes its OpenAPI specification, and you generate a typed client for each language from it.

Spec: `https://api.kronbase.dev/api/documentation.json`

### Authentication

- Every operation carries your project's API key in the `x-api-key` header.
- Operations performed on behalf of a user (`/api/auth/user`, notifications, user administration…) also carry `Authorization: Bearer <JWT>`, the token returned by `signin` and `refresh`.

### Generate the client

You need Docker. With [OpenAPI Generator](https://openapi-generator.tech):

```bash
curl -o openapi.json https://api.kronbase.dev/api/documentation.json

# Kotlin
docker run --rm -v "$PWD:/w" openapitools/openapi-generator-cli:v7.10.0 \
  generate -i /w/openapi.json -g kotlin -o /w/kotlin

# Swift
docker run --rm -v "$PWD:/w" openapitools/openapi-generator-cli:v7.10.0 \
  generate -i /w/openapi.json -g swift5 -o /w/swift

# Flutter / Dart
docker run --rm -v "$PWD:/w" openapitools/openapi-generator-cli:v7.10.0 \
  generate -i /w/openapi.json -g dart-dio -o /w/dart
```

Each operation has a stable `operationId` (`postAuthSignin`, `getAdminUsersById`…) used as the method name.

### Notes per language

- **Kotlin**: compiles as generated; set the API key in `ApiClient.apiKey["x-api-key"]`.
- **Swift**: uses `URLSession`; builds on macOS (it relies on Apple modules).
- **Dart / Flutter**: use the `dart-dio` generator, not `dart`. After generating, run `dart run build_runner build`.

### Limits

- The specification covers the HTTP API. Realtime (WebSocket) is not in OpenAPI and is currently only offered by the JavaScript SDK.
- There are no hand-maintained official SDKs yet; tell us what you need.


---

# Notifications


## Notifications

Kronbase stores in-app notifications in a `NOTIFICATIONS` table of your project, one row per notification and per user. Your backend creates them with a `service_role` key; each end user reads and marks their own with their access token. Nobody can see another user's notifications: every read and every update is filtered by the user ID in the token.

### Prerequisite: the NOTIFICATIONS table

The endpoints read and write a table called `NOTIFICATIONS` in your project's schema. Creating a project provisions the auth tables, not this one, so create it once (for example with `kronbase migration` or the dashboard's SQL runner):

```sql
CREATE TABLE NOTIFICATIONS (
  ID           NUMBER         GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  AUTH_USER_ID VARCHAR2(50)   NOT NULL REFERENCES AUTH_USERS(ID),
  TYPE         VARCHAR2(100),
  TITLE        VARCHAR2(200)  NOT NULL,
  BODY         VARCHAR2(1000),
  DATA         CLOB,
  READ         NUMBER(1)      DEFAULT 0 NOT NULL,
  CREATED_AT   TIMESTAMP      DEFAULT CURRENT_TIMESTAMP NOT NULL
);

CREATE INDEX idx_notifications_user   ON NOTIFICATIONS(AUTH_USER_ID);
CREATE INDEX idx_notifications_unread ON NOTIFICATIONS(AUTH_USER_ID, READ);
```

### Endpoints

All of them require `x-api-key`. Reading and marking also require `Authorization: Bearer <accessToken>`.

| Method and path | Who | Description |
|---|---|---|
| `POST /api/notifications` | `service_role` key | Creates a notification for a user |
| `GET /api/notifications` | User (JWT) | Lists the user's notifications, newest first |
| `GET /api/notifications/unread-count` | User (JWT) | Number of unread notifications |
| `PATCH /api/notifications/:id/read` | User (JWT) | Marks one notification as read |
| `PATCH /api/notifications/read-all` | User (JWT) | Marks all of the user's unread notifications as read |

### Send (backend)

Requires a `service_role` key; any other key gets `403` with code `FORBIDDEN`.

```typescript
import { createClient } from '@kronbase/client'

const admin = createClient('https://api.kronbase.dev/api', {
  serviceKey: process.env.KB_SERVICE_KEY!,
})

const { id } = await admin.notifications().send({
  authUserId: 'user-uuid',
  type: 'overtime.approved',
  title: 'Overtime approved',
  body: 'Your overtime request was approved.',
  data: { requestId: 123 },
})
```

```bash
curl -X POST https://api.kronbase.dev/api/notifications \
  -H "x-api-key: $KB_SERVICE_KEY" -H "Content-Type: application/json" \
  -d '{ "authUserId": "user-uuid", "type": "overtime.approved", "title": "Overtime approved", "body": "Your overtime request was approved.", "data": { "requestId": 123 } }'
```

| Field | Required | Notes |
|---|---|---|
| `authUserId` | yes | ID of the user (`AUTH_USERS.ID`, the `sub` of their token). It must exist; otherwise the insert fails with `500` and code `CREATE_NOTIFICATION_ERROR`. |
| `title` | yes | Up to 200 characters. |
| `type` | no | Free text up to 100 characters, to classify it (for example `overtime.approved`). |
| `body` | no | Up to 1000 characters. |
| `data` | no | Any JSON object; it is stored serialized as JSON. |

Response, status `201`:

```json
{ "success": true, "data": { "id": 42 } }
```

`send()` returns `{ id }` and throws an `Error` with the server's message if the request fails.

### List

```typescript
const { data, meta } = await kb.notifications().get({ unreadOnly: true, limit: 20, offset: 0 })
console.log(`${meta.unread} unread of ${meta.total}`)
```

```bash
curl "https://api.kronbase.dev/api/notifications?unreadOnly=true&limit=20&offset=0" \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>"
```

| Query parameter | Default | Meaning |
|---|---|---|
| `unreadOnly` | `false` | Only `true` filters to unread ones. |
| `limit` | `20` | Page size. The server sets no maximum for this endpoint. |
| `offset` | `0` | Rows to skip. |

```json
{
  "success": true,
  "data": [
    {
      "id": 42,
      "authUserId": "user-uuid",
      "type": "overtime.approved",
      "title": "Overtime approved",
      "body": "Your overtime request was approved.",
      "data": { "requestId": 123 },
      "read": false,
      "createdAt": "2026-11-01T10:30:00.000Z"
    }
  ],
  "meta": { "total": 1, "unread": 1 }
}
```

`meta.total` respects `unreadOnly`; `meta.unread` is always the user's total unread count.

Each element of `data` has the shape of the SDK's `Notification` type:

| Field | Type | Notes |
|---|---|---|
| `id` | number | Notification ID (the one `markRead()` takes). |
| `authUserId` | string | ID of the user it belongs to. |
| `type` | string or `null` | Free-text classification given at send time. |
| `title` | string | Title. |
| `body` | string or `null` | Body text. |
| `data` | object or `null` | The JSON object sent in `data`, already parsed. |
| `read` | boolean | `true` once marked as read. |
| `createdAt` | string | ISO 8601 date in UTC. |

> **Note:** The field names are camelCase, not the table's column names (`AUTH_USER_ID`, `CREATED_AT`, ...). If a stored `DATA` value is not valid JSON, `data` comes back as `null`.

### Count and mark as read

```typescript
const count = await kb.notifications().unreadCount()      // number
await kb.notifications().markRead(42)                     // one
const updated = await kb.notifications().markAllRead()    // how many were updated
```

```bash
curl https://api.kronbase.dev/api/notifications/unread-count \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>"
# { "success": true, "data": { "count": 3 } }

curl -X PATCH https://api.kronbase.dev/api/notifications/42/read \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>"
# { "success": true }

curl -X PATCH https://api.kronbase.dev/api/notifications/read-all \
  -H "x-api-key: $KB_ANON_KEY" -H "Authorization: Bearer <accessToken>"
# { "success": true, "data": { "updated": 3 } }
```

### Errors

| Status | Code | When |
|---|---|---|
| `401` | `UNAUTHORIZED` | Bearer token present but invalid or expired on a user endpoint |
| `400` | `QUERY_ERROR` | The request does not match the route schema: missing `Authorization` header on a user endpoint, missing `x-api-key` or `title`/`authUserId` on `POST` |
| `401` | `API_KEY_REQUIRED`, `INVALID_API_KEY` | Missing, unknown or revoked `x-api-key` |
| `403` | `FORBIDDEN` | `POST /api/notifications` with a key that is not `service_role` |
| `400` | `INVALID_ID` | The `:id` of `/read` is not a number |
| `404` | `NOT_FOUND` | The notification does not exist or does not belong to the user |
| `500` | `CREATE_NOTIFICATION_ERROR`, `GET_NOTIFICATIONS_ERROR`, `UNREAD_COUNT_ERROR`, `MARK_READ_ERROR`, `MARK_ALL_READ_ERROR` | Failure while executing the operation (for example, the table does not exist) |

### With cookies

If you use a client with a cookie adapter (see Auth model), `notifications()` sends the `access_token` cookie as the Bearer token on its own. With a plain client you can pass the token in the configuration:

```typescript
const kb = createClient('https://api.kronbase.dev/api', {
  apiKey: process.env.KB_ANON_KEY!,
  accessToken: userAccessToken,
})
```

> **Note:** Notifications are read on request: there is no push channel for them, so to react to new ones poll `unreadCount()`. Realtime can be scoped per user through RLS, but only on tables with policies and with a user token; it is not a ready-made per-user notification stream.


---

# Realtime


## Realtime

Realtime lets you subscribe to a `SELECT` on a table. The server sends you the current result when you subscribe and, afterwards, the full result again every time that result changes. Changes are detected by the Oracle database itself (Continuous Query Notification, CQN), with no polling.

> **Note:** Important change. A server with this release treats clients that send no user token as `anon`. On tables with RLS those clients see only what the policy allows a null user (usually nothing), same as REST. Upgrade `@kronbase/client` and give the realtime client the token (cookie adapter or `realtime.getAccessToken`, see "With the SDK"). Also, in the tests performed, subscribing to tables with an active RLS policy now works (before, registration failed on those tables).

> **Note:** On BYOC or dedicated deployments, `REALTIME_CQN_CLIENT_INITIATED` now defaults to `true` (CQN connection opened by the API). To go back to the inbound-callback mode, set `REALTIME_CQN_CLIENT_INITIATED=false`.

### Security model

Realtime applies the same access rules and the same RLS as `/api/query`. Each subscription runs with one of three identities:

| Identity | When | What it sees |
|---|---|---|
| `service` | `service_role` API key (the token does not change the identity) | Full access, same as REST |
| `anon` | `anon` API key without a valid user token | Only the project's public tables; on tables with RLS it sees what the policy allows a null user (usually nothing), same as REST |
| `user:<sub>` | `anon` API key plus a valid access JWT from the same project | That user's RLS view; non-public tables are allowed too |

- It is a WebSocket, not a REST endpoint: `wss://api.kronbase.dev/api/realtime`.
- Subscriptions are read-only: the server forces the operation to `SELECT` whatever you send.
- `anon` can only subscribe to public tables (`NOT_PUBLIC_TABLE` otherwise). The `*` wildcard does not count, as in REST.
- Auth tables (`AUTH_USERS`, `AUTH_SESSIONS`, ...) can never be subscribed to, and RBAC tables (`AUTH_ROLES`, ...) require a `service_role` key (`AUTH_TABLE_RESTRICTED`).
- An invalid token never silently downgrades to `anon`: the server answers `INVALID_TOKEN` (and closes with `4401` if there was no valid user identity). With a `service_role` key the token does not change the identity, but if you send one it is still validated.
- These rules apply to the main table and to every table in `query.joins`: `anon` cannot JOIN a non-public table, and nobody can JOIN an auth table (or an RBAC table without a `service_role` key).

> **Note:** RLS only filters tables that have a policy. A table without an RLS policy is fully visible: to `anon` if the table is public, and to every logged-in user otherwise. This is the same as in REST.

### With the SDK

Call `.subscribe()` on a `select()` builder, register the handlers, and call `.connect()`.

```typescript
import { createClient } from '@kronbase/client'

const kb = createClient('https://api.kronbase.dev/api', {
  apiKey: process.env.NEXT_PUBLIC_KB_KEY!,
})

const subscription = kb
  .from('PRODUCTOS')
  .select(['ID', 'NOMBRE', 'STOCK'])
  .eq('ACTIVO', 1)
  .subscribe()
  .on('change', (rows, meta) => {
    console.log(rows, meta)   // full, current result of the query
  })
  .on('error', (err) => console.error(err))

await subscription.connect()

// later
await subscription.unsubscribe()   // or disconnect(), same thing
```

| API | Description |
|---|---|
| `.subscribe()` | On `select()` builders. Returns a `Subscription`; throws if Realtime is disabled on the client. |
| `.on('change', (data, meta) => void)` | Called with the `data` and `meta` of every message, both for the initial data and for each later change (the handler does not tell them apart). |
| `.on('error', (error) => void)` | Called if `connect()` fails, if the server sends an error for that subscription (for example `SUBSCRIPTION_REVOKED` or `TOO_MANY_SUBSCRIPTIONS`), or if the token expires and no new one is available. |
| `await .connect()` | Opens the WebSocket if it was not open and sends the `subscribe` message. |
| `await .unsubscribe()` / `.disconnect()` | Sends `unsubscribe`, marks the subscription as disconnected and removes its handlers. |
| `await client.refreshRealtimeAuth()` | Tells the socket about a session change (see below). |

Client configuration, in the `realtime` option of `createClient`:

| Option | Default | Meaning |
|---|---|---|
| `enabled` | `true` | If `false`, `.subscribe()` throws `RealtimeClient not initialized`. |
| `reconnect` | `true` | Reopens the connection when it closes. |
| `reconnectDelay` | `1000` | Base delay in milliseconds between reconnection attempts. |
| `getAccessToken` | (none) | Function that gives the user's JWT to the socket (see "Where the token comes from"). |

> **Note:** `createServerClient` from `@kronbase/client` creates the client with Realtime disabled, because server processes do not keep WebSocket connections open. `createServerClient` from `@kronbase/ssr/server` does not pass the `realtime` option, so there Realtime stays enabled by default. For subscriptions use `createClient` or `createBrowserClient`.

The SDK derives the URL from the base URL: it replaces `http` with `ws` and appends `/realtime`. In the browser and on Node 22 or later it uses the native `WebSocket`; on older Node versions it falls back to the `ws` package.

#### Where the token comes from

The SDK sends an `auth` message with the user's JWT on every connection and reconnection, before re-sending the `subscribe` messages. It takes the token, in priority order, from:

1. `realtime.getAccessToken`, if you define it: it replaces everything else.
2. The `access_token` cookie of the cookie adapter, the same session the REST requests use (renewed with the refresh token in a single request shared with `getUser()`).
3. The client's static `accessToken` option.

If there is no token, the socket runs as `anon`.

When the session cookies are `httpOnly`, browser code cannot read `access_token`. The SDK writes the session cookies as `httpOnly`, so in a browser app (typically Next.js) the cookie adapter does not see the token and realtime would run as `anon`. The way out is to hand the token over from an endpoint of your own app:

```typescript
const kb = createClient('https://api.kronbase.dev/api', {
  apiKey: process.env.NEXT_PUBLIC_KB_KEY!,
  realtime: {
    getAccessToken: async ({ forceRefresh } = {}) => {
      // Your endpoint reads the httpOnly cookie on the server and returns the token.
      const res = await fetch(`/api/realtime-token${forceRefresh ? '?refresh=1' : ''}`)
      if (!res.ok) return null          // null = anonymous
      const { token } = await res.json()
      return token
    },
  },
})
```

`forceRefresh` is `true` when the server rejected the previous token (close `4401`): in that case your endpoint must renew the session instead of returning whatever token it has at hand. A provider that throws counts as "no token" when connecting; during a renewal the current identity is kept and the call is retried.

#### Renewal and expiry

- The SDK renews the token on the open socket about 60 s before its `exp`, calling the provider again and sending a new `auth`. The `subscribe` messages are not repeated.
- If the token expires without having been renewed, the server closes with `4401` (`TOKEN_EXPIRED`). The SDK asks for a new token once (with `forceRefresh: true`); if it is different, it reconnects immediately and re-subscribes. If there is no new one, it stops reconnecting and notifies the subscriptions' `error` handlers.
- A static `accessToken` cannot be renewed: when it expires the client disconnects and the reconnection fails with that error.
- After signing in or out call `await client.refreshRealtimeAuth()`: it re-reads the token and sends `auth` with the new token (or `token: null` if there is no session any more) without reconnecting. If the token did not change, it does nothing.

### Protocol

All messages are JSON text frames with a `type` field. The server rejects frames larger than 256 KiB by closing the connection with `1009`.

#### Connecting and authenticating

Connect to `wss://api.kronbase.dev/api/realtime`. The API key can be provided in two ways:

- `x-api-key` header on the upgrade request (clients that can set headers, such as the `ws` package on Node). It takes priority over the `apiKey` field. If the key is invalid, the server sends an `error` message with code `INVALID_API_KEY` and closes the connection with code `1008`.
- `apiKey` field in the `auth` and `subscribe` messages (the only option in browsers, which cannot set headers on a WebSocket). The SDK always uses this one.

The socket's project is fixed by the first key resolved; a key from another project on the same socket yields `PROJECT_MISMATCH`.

If the connection does not complete a successful `subscribe` or an accepted `auth` within 5 seconds, the server sends `{ "type": "error", "error": "Authentication timeout", "code": "AUTH_TIMEOUT" }` and closes with `1008`.

#### Client to server

Authenticate the user (optional; without it the identity is `anon`, or `service` with a `service_role` key):

```json
{ "type": "auth", "apiKey": "<KB_ANON_KEY>", "token": "<access jwt>" }
```

- `token` must be a valid, unexpired access JWT from the same project as the key; it is verified the same way as in `/api/query`. Never put it in the URL or in headers.
- An explicit `"token": null` logs out: subscriptions become `anon`, and those `anon` cannot open are cancelled with `SUBSCRIPTION_REVOKED`.
- An `auth` without the `token` field, or with an empty or non-string token, counts as an invalid token.
- You can send `auth` several times on the same connection (renewal or user switch).

Subscribe:

```json
{
  "type": "subscribe",
  "subscriptionId": "6f1d9a52-0c53-4c1e-9f0a-2d8f6c1a7b10",
  "apiKey": "<KB_ANON_KEY>",
  "query": {
    "table": "PRODUCTOS",
    "select": ["ID", "NOMBRE", "STOCK"],
    "filters": [{ "column": "ACTIVO", "operator": "eq", "value": 1 }]
  }
}
```

- `query.table` is required (`MISSING_TABLE`). `query` accepts the same fields as a `/query` request; the same identifier validation applies, and a violation comes back as an `error` with the validation code.
- You choose `subscriptionId` (a string of up to 128 characters, otherwise `INVALID_MESSAGE`); if you omit it the server generates a UUID. It comes back in every message of that subscription. If you reuse an active `subscriptionId` on the same connection, the new subscription replaces the old one.
- The subscription's identity is decided at the moment you subscribe, using the key and the last accepted `auth`.
- The data sent is the result of running the subscription's full query (including `orderBy`, `limit` and filters).

Cancel the subscription:

```json
{ "type": "unsubscribe", "subscriptionId": "6f1d9a52-0c53-4c1e-9f0a-2d8f6c1a7b10" }
```

#### Server to client

| `type` | Content | When |
|---|---|---|
| `authenticated` | `expiresAt` (epoch seconds, or `null`) | Reply to an accepted `auth`; `null` after `token: null`. |
| `initial` | `subscriptionId`, `data`, `meta`, `timestamp` | With the query result when you subscribe, and again when the subscription's identity changes because of an `auth`. |
| `subscribed` | `subscriptionId` | The subscription is registered. Arrives after `initial`. |
| `change` | `subscriptionId`, `data`, `meta`, `timestamp` | When the result for your identity changes. `data` is the new full result, not a diff. |
| `unsubscribed` | `subscriptionId` | Reply to `unsubscribe`. |
| `error` | `error`, `code`, `subscriptionId` (optional) | Any failure. |

```json
{
  "type": "change",
  "subscriptionId": "6f1d9a52-0c53-4c1e-9f0a-2d8f6c1a7b10",
  "data": [ { "ID": 1, "NOMBRE": "Camisa", "STOCK": 4 } ],
  "meta": { "total": 1 },
  "timestamp": "2026-11-03T14:00:00.000Z"
}
```

`timestamp` is an ISO date generated by the server; `data` and `meta` have the same shape as the `POST /api/query` response (`meta.total` is the number of rows matching the filters; `limit` and `offset` appear only if the query defines them).

Error codes you can receive:

| `code` | Cause |
|---|---|
| `INVALID_API_KEY` | Unknown or revoked key |
| `API_KEY_REQUIRED` | `auth` or `subscribe` with no key in the header or in `apiKey` |
| `INVALID_TOKEN` | The `auth` token is invalid, expired, from another project, or missing |
| `PROJECT_MISMATCH` | The key belongs to a different project than this connection |
| `MISSING_TABLE` | `query.table` is missing |
| `INVALID_TABLE` | Invalid table name |
| `AUTH_TABLE_RESTRICTED` | Auth table, or RBAC table without a `service_role` key |
| `NOT_PUBLIC_TABLE` | `anon` identity on a table that is not public |
| `SUBSCRIPTION_REVOKED` | After an `auth` (for example `token: null`), the new identity can no longer access some table of the query (including those in `joins`): the subscription is cancelled |
| `TOO_MANY_SUBSCRIPTIONS` | The connection already has the maximum number of subscriptions (default 20) |
| `TOO_MANY_PENDING_MESSAGES` | Too many queued messages: the server closes with `1008` |
| `REALTIME_UNAVAILABLE` | Realtime is not available for the project (for example CQN is unavailable) or the server is shutting down |
| `REALTIME_OVERLOADED` | The server is saturated; retry later |
| `UNKNOWN_SUBSCRIPTION` | `unsubscribe` with a `subscriptionId` this connection does not have |
| `INVALID_MESSAGE` | A message that is not a JSON object, or an invalid `subscriptionId` |
| `UNKNOWN_MESSAGE_TYPE` | Unknown `type` |
| `AUTH_TIMEOUT` | No `subscribe` or accepted `auth` within 5 seconds |
| `INTERNAL_ERROR` | Internal failure while validating the key from the upgrade's `x-api-key` header: the server closes with `1011` |
| others | The query validation code (for example `INVALID_NAME` for an invalid table or column name) |

WebSocket close codes:

| Code | Reason |
|---|---|
| `4401` | `INVALID_TOKEN` (invalid token with no earlier valid user identity) or `TOKEN_EXPIRED` (the token expired without a renewed `auth`). Send a new token and reconnect. |
| `1008` | Policy: `INVALID_API_KEY` on upgrade, `AUTH_TIMEOUT` or `TOO_MANY_PENDING_MESSAGES` |
| `1009` | Frame larger than 256 KiB |
| `1011` | Internal server error (`INTERNAL_ERROR`) |

#### Ordering and per-connection limits

- Messages on a connection are processed serially, in arrival order: an `auth` is never interleaved with a half-done `subscribe`. A slow `initial` can delay the messages behind it.
- Maximum subscriptions per connection: `REALTIME_MAX_SUBSCRIPTIONS_PER_SOCKET` (default 20). If you need more, open another connection (another client).
- Pending messages (queued or in progress): at most twice that cap plus 10 (50 by default) and at most 1 MiB in total. This fits a normal reconnection burst (`auth` plus one `subscribe` per subscription). Above that, the server sends `TOO_MANY_PENDING_MESSAGES`, closes with `1008` and drops the queued messages; the SDK reconnects with its growing delay and re-sends `auth` and the `subscribe` messages.
- After a reconnection the server remembers nothing from the previous connection: `auth` and `subscribe` must be sent again. The SDK does it by itself, and you receive a new `initial`.

### Subscription behavior

- Identity is decided when you subscribe. If an `auth` with another user, or `token: null`, arrives later, the server moves each subscription to the new identity and sends a new `initial` with its result; if the new identity cannot access the table, it cancels the subscription with `SUBSCRIPTION_REVOKED` (no `initial`).
- Results are computed per identity: on a change, the query runs once for each distinct identity (`service`, `anon`, `user:<sub>`) and the result is sent only to that identity's subscriptions. Several clients with the same user share that execution.
- Notifications are grouped (debounced) before executing, so a burst of changes produces a single message with the latest state.
- A `change` always carries the full result for that identity, as before. If the result for an identity did not change (for example, the DML touched rows it cannot see), no message is sent.
- A subscription can carry expressions in `select()` (see "Expressions in SELECT" in the database documentation): they are recomputed on every re-execution of the query. Since the CQN registration is on the main table, changes only in joined tables do not notify.
- Subscriptions to the same table with the same full query (columns, filters, `orderBy`, `limit`, ...) share the CQN registration; different queries have different registrations.

### Raw example (Node)

```typescript
import WebSocket from 'ws'

const ws = new WebSocket('wss://api.kronbase.dev/api/realtime', {
  headers: { 'x-api-key': process.env.KB_ANON_KEY! },
})

ws.on('open', () => {
  // The user's access JWT (optional; without it the identity is anon)
  ws.send(JSON.stringify({ type: 'auth', token: process.env.USER_ACCESS_TOKEN! }))
  ws.send(JSON.stringify({
    type: 'subscribe',
    subscriptionId: 'orders-1',
    query: { table: 'PEDIDOS', select: ['ID', 'ESTADO'] },
  }))
})

ws.on('message', (raw) => {
  const msg = JSON.parse(raw.toString())
  if (msg.type === 'initial' || msg.type === 'change') console.log(msg.data)
  if (msg.type === 'error') console.error(msg.code, msg.error)
})
```

### Reconnection

When the connection closes and `reconnect` is not `false`, the SDK retries up to 5 times. Attempt `n` waits `reconnectDelay * n` ms (1 s, 2 s, 3 s, 4 s and 5 s with the default value). A successful connection resets the counter. After the fifth failed attempt it stops and logs `Max reconnect attempts reached`. A `4401` close follows the path described in "Renewal and expiry". `createClient()` does not expose the `RealtimeClient` (it is private), so there is no public client-level `disconnect()`. If you use `RealtimeClient` directly (exported from `@kronbase/client`), its `disconnect()` closes the socket and cancels the pending reconnection and retries: it does not reopen or re-subscribe.

> **Note:** On reconnect, the SDK sends `auth` and automatically re-sends the `subscribe` message of every active subscription, with the same `subscriptionId`, so registered `.on('change')` handlers keep working without any action. Since the server sends an `initial` on every `subscribe`, a new `initial` snapshot reaches the same handler after each reconnection: use it to resync your state, because changes that happened while you were disconnected are not replayed. Subscriptions cancelled with `unsubscribe()` or revoked by the server are not restored. The SDK has no event announcing that a reconnection happened.

> **Note:** Per-subscription server errors (`SUBSCRIPTION_REVOKED`, `TOO_MANY_SUBSCRIPTIONS`, `NOT_PUBLIC_TABLE`, ...) are also written to the console and reach that subscription's `.on('error')` handler. Fatal subscription errors (`SUBSCRIPTION_REVOKED`, `PROJECT_MISMATCH`, `NOT_PUBLIC_TABLE`, `INVALID_QUERY`, `AUTH_TABLE_RESTRICTED`, `INVALID_TABLE`) also remove the subscription from the client, which is not re-sent on reconnect.

### Operations and BYOC

Realtime limits are configured with environment variables of the API process. On Kronbase Cloud the Kronbase operator sets them; on a BYOC or dedicated deployment you set them yourself, on the API container. All are optional. Numeric ones must be positive integers written with digits only; any other value is ignored and the default is used, and times are capped at 2^31-1 ms. `REALTIME_CQN_CLIENT_INITIATED` is a boolean: `true`/`1` or `false`/`0` (case-insensitive); any other value uses the default.

| Variable | Default | Meaning |
|---|---|---|
| `REALTIME_DEBOUNCE_MS` | `100` | Wait after a notification to group bursts before re-running the query |
| `REALTIME_MAX_WAIT_MS` | `1000` | Cap on the wait since the first pending notification, even if more keep arriving. Also the wait before retrying a round postponed by overload |
| `REALTIME_MAX_CONCURRENT_EXEC` | tenant pool size minus 2 (minimum 1) | Simultaneous realtime executions per tenant. Keep it below the tenant pool size (5), or realtime can take every connection REST uses |
| `REALTIME_MAX_QUEUE` | `200` | Queued executions per tenant; above it the round is postponed (`REALTIME_OVERLOADED` on the `initial`) |
| `REALTIME_MAX_SUBSCRIPTIONS_PER_SOCKET` | `20` | Subscriptions per connection (and the base of the pending-message cap: twice it plus 10) |
| `REALTIME_RESYNC_INTERVAL_S` | off (`0`) | If set, each registration re-runs its queries every N seconds even with no notification |
| `REALTIME_CQN_CLIENT_INITIATED` | `true` | With `true` the client (the API) opens the CQN connection toward the database, with no inbound callbacks. With `false` the database sends inbound callbacks to the API process (untested mode) |

Notes on CQN:

- The API subscribes at object level: any DML on the subscribed table triggers a re-execution for each connected identity, and the result is compared with the last one sent to avoid noise.
- It requires `GRANT CHANGE NOTIFICATION` for the tenant user (usually granted when the project is provisioned; if it is missing, the subscription fails with `REALTIME_UNAVAILABLE`) and the Oracle "thick" driver in the API.
- The "thick" driver runs database calls on the libuv threadpool, which has 4 threads by default for the whole process. Raise `UV_THREADPOOL_SIZE` on the API container (the API image sets `16`).
- If CQN is not available (for example, the database does not allow it), the subscription fails with `REALTIME_UNAVAILABLE`.
- With the default (`REALTIME_CQN_CLIENT_INITIATED=true`) the database does not need to reach the API process.
- `REALTIME_RESYNC_INTERVAL_S` is for bounding staleness when row visibility depends on other tables (see limitations).

### Limitations

- **Eventual consistency when visibility depends on other tables.** CQN only notifies changes on the subscribed table. If an RLS predicate or your query depends on another table (for example a membership table), a change only in that other table produces no notification and subscriptions are not updated until the subscribed table changes next. Options: also subscribe to that other table, or enable `REALTIME_RESYNC_INTERVAL_S` to bound the lag.
- **One API process per deployment.** There is no coordination between API replicas: subscriptions and CQN registrations live in the process serving the connection.
- **Session revocation is not checked on the socket.** Once the token is accepted, the connection keeps the identity until its `exp` (when it closes with `4401`), even if the session is signed out or revoked earlier.
- **Static tokens are not renewed** (a fixed `accessToken` on the client).
- **Validated in tests with Oracle 26ai Free.** CQN behavior with RLS was checked on that version; others were not tested. Those tests only exercised the client-initiated CQN connection, which is now the default. The inbound-callback mode (`REALTIME_CQN_CLIENT_INITIATED=false`) was not exercised in tests.


---

# PL/SQL: functions and procedures


## PL/SQL: functions and procedures

The Data API can **call** stored procedures and functions that already exist in your project's schema. You use the `PROCEDURE` and `FUNCTION` operations of `POST /api/query` (or inside `POST /api/transaction`). Creating or changing those objects is not done this way: see "What is not supported" below.

### Request

A call is a `/query` body with `operation` set to `PROCEDURE` or `FUNCTION` and a `plsql` object. The request schema requires the `table` field even though it is unused: send an empty string.

```bash
curl -X POST https://api.kronbase.dev/api/query \
  -H "x-api-key: $KB_SERVICE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "table": "",
    "operation": "FUNCTION",
    "plsql": {
      "name": "PKG_USER.GET_NAME",
      "parameters": [
        { "name": "p_user_id", "value": 123, "direction": "IN" }
      ],
      "returnType": "STRING"
    }
  }'
```

| Field | Rule |
|---|---|
| `plsql.name` | Name of the procedure or function: `NAME` or `PACKAGE.NAME`. Only letters, digits and `_`, starting with a letter or `_` (at most one dot). Any other format, or a routine that cannot be called (see "Authentication and security"), returns `403` with `INVALID_PLSQL_NAME`. |
| `plsql.parameters` | Optional array. They are passed to the call in the order you send them, as bind variables. |
| `parameters[].name` | Parameter name (same format rules as a column name). Any other format returns `403` with `INVALID_PARAMETER_NAME`. |
| `parameters[].direction` | `IN`, `OUT` or `IN_OUT`. Required. |
| `parameters[].value` | Input value, for `IN` and `IN_OUT`. |
| `parameters[].type` | `STRING`, `NUMBER`, `DATE`, `CLOB`, `BLOB` or `CURSOR`. For `OUT` and `IN_OUT` it is the Oracle type of the bind; if omitted, `STRING` is used. |
| `parameters[].maxSize` | Maximum size for a `STRING`/`CLOB` `OUT` or `IN_OUT` parameter. |
| `plsql.returnType` | `FUNCTION` only: type of the returned value, with the same values as `type`. Defaults to `STRING`. |

The server builds the call with the already validated `name` and the values as bind variables:

```sql
-- PROCEDURE
BEGIN PKG_USER.CREATE_USER(:p_username, :p_user_id); END;

-- FUNCTION
BEGIN :return_value := PKG_USER.GET_NAME(:p_user_id); END;
```

Parameters are passed **by position**, in the order of the `parameters` array; its `name` is only the bind name, it is not used as `p_user_id => ...`. Order them like the routine's signature.

### Response

```json
{
  "success": true,
  "data": "Ana",
  "plsql": {
    "returnValue": "Ana"
  }
}
```

| Operation | `data` | `plsql` |
|---|---|---|
| `FUNCTION` | The return value | `returnValue`, plus `outParameters` / `cursor` if any |
| `PROCEDURE` | `{}` | `outParameters` / `cursor` if any |

- `plsql.outParameters` is an object `{ parameterName: value }` with the `OUT` and `IN_OUT` parameters. It is omitted when there are none.
- `plsql.cursor` holds the rows of an `OUT` parameter with `type: "CURSOR"` (a `REF CURSOR`). If you declare more than one `CURSOR` parameter, only the first one is returned.
- A call to `/query` does an automatic `COMMIT` when it finishes. Inside `/transaction` it does not: see below.

### Procedure with OUT parameters and a cursor

```json
{
  "table": "",
  "operation": "PROCEDURE",
  "plsql": {
    "name": "PKG_REPORT.TOP_CUSTOMERS",
    "parameters": [
      { "name": "p_min_total", "value": 1000, "direction": "IN" },
      { "name": "p_count",     "direction": "OUT", "type": "NUMBER" },
      { "name": "p_rows",      "direction": "OUT", "type": "CURSOR" }
    ]
  }
}
```

```json
{
  "success": true,
  "data": {},
  "plsql": {
    "outParameters": { "p_count": 2 },
    "cursor": [
      { "ID": 1, "NAME": "Ana" },
      { "ID": 2, "NAME": "Luis" }
    ]
  }
}
```

> **Note:** The server returns `OUT` values as the Oracle driver delivers them, without converting them. For text, use `STRING` with `maxSize` instead of `CLOB`/`BLOB`.

### With the SDK

`QueryBuilder` offers `procedure(name, parameters?)` and `function(name, parameters?, returnType = 'STRING')`. Since there is no table, start with `from('')`.

```typescript
import { createClient } from '@kronbase/client'

const kb = createClient('https://api.kronbase.dev/api', {
  apiKey: 'KB_ANON_KEY',
  accessToken: userAccessToken,
})

// FUNCTION
const { data, plsql } = await kb.from('').function('PKG_USER.GET_NAME', [
  { name: 'p_user_id', value: 123, direction: 'IN' },
], 'STRING').execute()
// data === plsql.returnValue

// PROCEDURE with OUT
const res = await kb.from('').procedure('PKG_USER.CREATE_USER', [
  { name: 'p_username', value: 'john', direction: 'IN' },
  { name: 'p_user_id', direction: 'OUT', type: 'NUMBER' },
]).execute()
console.log(res.plsql?.outParameters?.p_user_id)
```

`execute()` throws an exception with the server message if the response is not `2xx`, like the rest of the queries. `build()` returns the request without sending it, to use it in a transaction.

### Authentication and security

- Authentication is the same as `/query`: `x-api-key` always. With an `anon` key a Bearer token is also required. Since a PL/SQL call has no table, it cannot use the public-table exception: without a token it returns `401` with `AUTH_REQUIRED`. With `service_role` no token is needed. See the Auth model section.
- **Only the project's own routines.** With an `anon` key (and token), the routine must belong to the project's schema: a standalone procedure or function (`NAME`) or a member of a project package (`PACKAGE.NAME`). The server checks the schema's dictionary before calling. Routines in other schemas, public synonyms and Oracle packages are rejected with `403` and `INVALID_PLSQL_NAME`, with the same message whether the routine does not exist or is not the project's. `PACKAGE.NAME` is always read as a package: do not prefix the schema name.
- **Oracle and vendor packages cannot be called**, with any key (`service_role` included): any name whose first segment is `SYS`, `SYSTEM`, `HTP`, `HTF`, `OWA`, `XDB`, `LT`, `ORDSYS`, `ORDPLUGINS`, `ORDDATA`, `CTXSYS`, `MDSYS`, `WMSYS`, `LBACSYS`, `DVSYS`, `OLAPSYS`, `OJVMSYS`, `AUDSYS` or `GSMADMIN_INTERNAL`, or starts with `DBMS_`, `UTL_`, `OWA_`, `CTX_`, `XDB`, `APEX_`, `SDO_`, `ORD_`, `ODCI`, `WWV_` or `XS_` is rejected with `403` and `INVALID_PLSQL_NAME`. If you need their functionality, wrap it in a project routine (created by migration) that exposes only what is needed.
- **Oracle-maintained schemas, with any key.** Besides the list above, before calling the server checks the dictionary: if the first segment of the name is not a project object and resolves to an Oracle-maintained schema (through a public or private synonym, or because it is that schema's name), the call is rejected with `403` and `INVALID_PLSQL_NAME`. This way Oracle packages published under other names cannot be reached either.
- With `service_role` (a trusted key) the routine does not have to belong to the project: any routine the project's connection can execute can be called (for example, from another non-Oracle schema with `EXECUTE` granted), except the Oracle ones described above.
- Per-table checks (for example `AUTH_TABLE_RESTRICTED`) do not apply to a PL/SQL call because there is no table; what the routine touches is decided by its own code.
- The call runs on the same connection as the rest of the queries, with the token user's context (or unrestricted for `service_role`) for the RLS policies the database evaluates.
- You can only invoke by name. There is no operation to send anonymous PL/SQL blocks or arbitrary SQL through `/query`.
- A `plsql.name` or parameter name with an invalid format is rejected with `403` before anything runs.

> **Note:** A project routine runs with the project schema's privileges and can read any table in the schema, auth tables included. Review what each routine exposes before letting an end user call it.

> **Note:** Naming your own routines. A project package or routine whose name (the first segment) matches the list above, for example `DBMS_REPORTS`, `UTL_DATES`, `XS_CALC` or `XDBUTIL`, cannot be called through `plsql`: rename it. Routines created with quoted lowercase or mixed-case names (`CREATE PROCEDURE "myProc"`) cannot be called either: the name is always read in uppercase. Create them unquoted.

### Errors

| Status | Code | When |
|---|---|---|
| `403` | `INVALID_PLSQL_NAME` | `plsql.name` does not match the format, is an Oracle/vendor package or resolves to an Oracle-maintained schema, or (`anon` key) the routine does not exist or is not owned by the project's schema. Always with the same message, which does not repeat the name |
| `404` | `PLSQL_ROUTINE_NOT_FOUND` | Oracle did not find the routine when calling it (for example, with `service_role` and a name that does not exist). Without the Oracle text |
| `403` | `INVALID_PARAMETER_NAME` | A parameter name does not match the format |
| `400` | `QUERY_ERROR` | The `plsql` object is missing for `PROCEDURE`/`FUNCTION`, or the body does not match the schema |
| `500` | `DB_ERROR` | Oracle returned an error (`ORA-`, `NJS-`, `DPI-`), for example the routine raises an exception; the detail stays only in the server logs |
| `403` | `RLS_VIOLATION` | The routine wrote a row outside the scope of the user's policy (`ORA-28115`) |

### Inside a transaction

In `POST /api/transaction`, `PROCEDURE` and `FUNCTION` operations mix with `INSERT`, `UPDATE`, etc. They run on the same connection and **without their own commit**: the `COMMIT` happens at the end if all of them succeed, and a failure in any of them also rolls back what the routine did. In the response, `results[i]` has the same shape as above (`data` and `plsql`).

```typescript
const result = await kb.transaction([
  kb.from('ORDERS').insert({ STATUS: 'NEW' }).build(),
  kb.from('').procedure('PKG_STOCK.RESERVE', [
    { name: 'p_sku', value: 'ABC-1', direction: 'IN' },
    { name: 'p_qty', value: 2, direction: 'IN' },
  ]).build(),
])
```

Two limits of references between operations: a `$ref` can only go in `data` and in the `value` of filters, so it cannot be used as the `value` of a PL/SQL parameter; and the result of a PL/SQL operation cannot be referenced either. Before the first operation runs, every routine in the transaction is checked: if any cannot be called, the request returns `403` with `INVALID_PLSQL_NAME` and no operation runs. If a PL/SQL operation fails inside a transaction, the response is `success: false` with `code: "TRANSACTION_FAILED"` and `failedAt` (see the Transactions section). In that case `error` does not carry the raw Oracle text: it is a generic message, unless the routine raised its own error with `RAISE_APPLICATION_ERROR` (`ORA-20000` to `ORA-20999`), whose text alone is returned. If the routine does not exist, `code` is `PLSQL_ROUTINE_NOT_FOUND`.

### What is not supported

- **Creating or changing functions and procedures through the Data API.** `/query` and `/transaction` only invoke them. To create them use the dashboard SQL runner or `kronbase migration`: both accept `CREATE [OR REPLACE] PROCEDURE`, `FUNCTION`, `PACKAGE` and `PACKAGE BODY`, as well as `TRIGGER`, `VIEW`, etc. In migration files, end each PL/SQL unit with a line holding only `/` (see the CLI section).
- **Anonymous blocks** (`BEGIN ... END;`) and arbitrary SQL through `/query`.
- **Named parameters** (`p_x => value`): parameters are passed by position.
- **More than one output cursor** per call: only the first is returned.
- **Realtime subscriptions** to PL/SQL calls: realtime only accepts `SELECT`.


---

# BYOC and dedicated deployment


## BYOC and dedicated deployment

A **dedicated deployment** (BYOC, "Bring Your Own Cloud") runs the Kronbase engine inside your own OCI tenancy, against your own Autonomous Database (ADB) and your own Object Storage. Your data does not live on Kronbase Cloud. Administration (creating projects, API keys, database, email) is still done from the `kronbase.dev` dashboard: you don't get a dashboard of your own.

A single deployment can host several of your projects, with the same one-Oracle-schema-per-project model as Kronbase Cloud.

### What is created in your account

The Terraform stack (packaged for OCI Resource Manager) creates, in the compartment you choose:

| Resource | Detail |
|---|---|
| Network | A VCN with a private subnet. The VM has no public IP and there is no public ingress by default |
| Autonomous Database | `adb_ecpu_count` ECPUs (default 2, minimum 2) and `adb_data_storage_size_in_tbs` TB (default 1) |
| Object Storage | A bucket named `<customer_name>-kronbase-storage` |
| VM | A `VM.Standard.A1.Flex` instance (arm64, 2 OCPU, 12 GB) running Oracle Linux 9 |
| Containers | `kronbase-api` (the Kronbase API, `api-dataplane` image), `kronbase-updater` (the updater, `updater` image) and `cloudflared` |

Access from `kronbase.dev` to your VM goes through a **Cloudflare tunnel** that the VM itself opens outbound, so no inbound port needs to be opened. If you need SSH, the optional `admin_cidr_block` variable opens port 22 for that CIDR; when empty (the default) there is no inbound SSH.

### Requirements

- A Kronbase account on the **Enterprise** plan. Registering the dedicated deployment (and downloading its stack) is rejected with `403` and the body `{ "error": "Requiere plan Enterprise" }` for accounts on other plans (the API returns this message in Spanish).
- An OCI tenancy with access to Resource Manager and permission to create the resources above.
- Your deployment's Cloudflare tunnel: Kronbase creates it in its own Cloudflare account when provisioning and gives you its hostname and token (you do not create one). The tunnel's public hostname rule must point to `http://localhost:3000` **limited to the path `^/platform/`** and end with the final catch-all `http_status:404`. The tunnel publishes to the internet whatever its rule matches, and the VM has no public IP: without the restriction, anyone could reach your instance's whole API (Data API, authentication, `/health`) from the internet. The dashboard only uses the `/platform/customers/me/...` routes through the tunnel; your apps do not go through it (see [Using the deployment](#using-the-deployment)).

  **How to check it** (no key needed; replace the hostname with your tunnel's):

  ```bash
  curl -s -o /dev/null -w '%{http_code}\n' https://your-domain/health                              # expected: 404
  curl -s -o /dev/null -w '%{http_code}\n' https://your-domain/api/documentation.json              # expected: 404
  curl -s -o /dev/null -w '%{http_code}\n' https://your-domain/platform/customers/me/projects      # expected: 401 (reachable, requires a key)
  ```
- An OCI API signing key for a user in your tenancy with Object Storage permissions on the bucket the stack creates. You generate it in the OCI console (Identity, Users, your user, API Keys) and you need the tenancy OCID, the user OCID, the fingerprint, the PEM private key and the region. Without it, file storage is disabled on the instance; the rest of the API works the same.

### Provision

1. In the dashboard open "Remote stack (dedicated deployment)" and enter your company name and the tunnel hostname and token that Kronbase gave you when provisioning.
2. The dashboard registers the deployment and shows its **control key only once**: save it. It also downloads `kronbase-dedicated-deployment.zip`, with the `deployment_id`, the `control_key`, the tunnel token, and the image registry and image values already loaded as defaults of the form.
3. In the OCI Console go to Developer Services, Resource Manager, Stacks, Create Stack, My Configuration, and upload the zip.
4. Fill in the fields that belong to your account: compartment, region, ADB admin password and the OCI credentials for Storage.
5. Terraform Actions, Plan, review and Apply.

> **Note:** The control key and the tunnel token are secrets. Sensitive stack variables are marked as such in Resource Manager. The zip contains your values, so do not commit it to a repository.

When the VM starts, the API sends a heartbeat to the Kronbase control plane. The deployment status in the dashboard moves from `PENDING` to `ACTIVE`.

### Status

| Status | Meaning |
|---|---|
| `PENDING` | Registered, no heartbeat received yet: the VM is not running yet or the tunnel has not connected |
| `ACTIVE` | Connected. You can create projects in it |
| `STALE` | It was connected but the last heartbeat is more than 15 minutes old. Check that the VM is on and the tunnel is active |

The heartbeat is sent at startup and then every 5 minutes, and it is best-effort: a lost one is retried on the next tick. It includes the version of the running API, which the dashboard shows.

### Using the deployment

With the deployment `ACTIVE`, the "New project" dialog asks where to create the project: Kronbase Cloud or "My dedicated infrastructure (BYOC)". A dedicated project is created as a schema in your ADB. Its detail (API keys, database, buckets, email) is managed from the same dashboard, which forwards the operations to your instance through the tunnel. The project list is read live from your instance, so if the VM or the tunnel does not respond the dashboard gets a `502`.

In a dedicated project, the email domain shows the same DNS records (DKIM, SPF and DMARC) as on Kronbase Cloud; the SPF value depends on the OCI Email Delivery region configured on your instance (`OCI_REGION`). See [Email](/en/docs/email#domain-dns-records).

Your apps use the project's Data API like any other (`x-api-key`, see Auth model), but **not through the tunnel**: they use the instance's **private** IP address, inside your VCN. The tunnel only carries control-plane traffic (dashboard ↔ instance). The stack does not return that IP as a Terraform output: you can see it in the OCI console (Compute, Instances, your instance, primary VNIC, private IP).

Exporting a project's data (`kronbase pull --data`) has to be enabled by whoever operates the deployment; if it is not enabled, the CLI says so.

### Images and architectures

The publishing workflow builds each image for `linux/amd64` and `linux/arm64` and publishes them to GitHub Container Registry:

| Image | Use |
|---|---|
| `ghcr.io/kronbase/api-dataplane` | The engine for BYOC. It does not include the central administration code |
| `ghcr.io/kronbase/api-local` | The engine for `kronbase start`: same as `api-dataplane`, but it only starts in development mode |
| `ghcr.io/kronbase/api` | Full variant, used by Kronbase Cloud |
| `ghcr.io/kronbase/dashboard` | Dashboard of the local stack (`kronbase start`) |
| `ghcr.io/kronbase/oci-storage-emulator` | OCI Object Storage emulator of the local stack |
| `ghcr.io/kronbase/dev-idp` | Test identity provider of the local stack (`kronbase start --dev-idp`); development only, not used in BYOC |
| `ghcr.io/kronbase/updater` | BYOC updater: replaces the API container with a new version and updates `cloudflared`, with rollback |

Tags: `latest` points to the latest release (a `cli-v*` tag), `dev` to the latest build of the main branch, and a manual build can carry its own tag. In addition, every release and every manual build publish a fixed version tag of the form `<version>-<sha8>` (for example `0.4.1-ab12cd34`): it is the version the dashboard shows and, together with `latest`, the only tag form the updater accepts. The packages are private. BYOC VMs pull them from `ghcr.io` with the read-only token Kronbase issues (see «ghcr.io token»); for the local stack, images are pulled from `registry.kronbase.dev` with your Kronbase token (see Installation). From that registry every plan can pull `api-local`, `dashboard`, `oci-storage-emulator` and `dev-idp`; `api-dataplane` and `updater` belong to the Enterprise plan. The stack zip ships `ghcr.io/kronbase/api-dataplane:latest` as the default for `docker_image`.

Because the images are multi-architecture, they work the same on an arm64 or amd64 host. The VM the Terraform module creates is arm64 (shape `VM.Standard.A1.Flex`, which the module fixes in code; it is not a variable).

### API environment variables

The stack injects them for you when it creates the container; you don't need to write them. Only names are listed:

| Variable | Purpose |
|---|---|
| `DEDICATED_MODE` | `true` enables dedicated mode (accepts the control plane's control key and sends the heartbeat) |
| `DEPLOYMENT_ID`, `CONTROL_KEY`, `CONTROL_PLANE_URL` | Deployment identity and heartbeat target. With `DEDICATED_MODE=true` they are required: if one is missing the API does not start |
| `DB_CONNECT_STRING`, `DB_USER`, `DB_PASSWORD` | Connection to your ADB |
| `PLATFORM_ADMIN_USER`, `PLATFORM_ADMIN_PASSWORD` | ADB administrator user used to create the project schemas |
| `AUTH_JWT_SECRET`, `PLATFORM_MASTER_KEY` | Secrets that Terraform generates randomly |
| `OCI_TENANCY_ID`, `OCI_USER_ID`, `OCI_FINGERPRINT`, `OCI_PRIVATE_KEY`, `OCI_REGION`, `OCI_NAMESPACE`, `OCI_BUCKET_NAME` | Object Storage access |
| `OCI_COMPARTMENT_ID` | OCI compartment (the stack's `compartment_ocid`); the API also uses it for email domains |
| `CORS_ORIGIN` | Allowed origins (the stack uses `*`) |
| `PUBLIC_API_URL` | Public URL of your API (the tunnel hostname, `https://your-domain`). New stacks already include it; the callback URL of the sign-in providers is built from it. That public browser flow needs the callback reachable from the internet, and the tunnel's default rule (`^/platform/`) does **not** expose it: for providers without an own redirect URI you must add an extra, optional path rule to the tunnel for `^/api/auth/oauth/[^/]+/[^/]+/callback$` (the `GET` and the `POST` Apple uses), knowing that it exposes that callback to the internet; it does not expose start, exchange, token or `complete`. For a private deployment the recommended path is the private flow, with an own redirect URI (see "Private flow: the API can stay private" in "Your instance settings"); without `PUBLIC_API_URL` only those providers can be enabled |
| `CONTROL_PLANE_ENABLED` | The `api-dataplane` image ships it as `false` |
| `REALTIME_*` (optional) | Realtime limits you can tune yourself, for example `REALTIME_CQN_CLIENT_INITIATED` (see the Realtime section) |

### Database service level per project

Each project connects to your Autonomous Database with a service level, which sets the priority and concurrency of its connections:

- `low`: more concurrency, less priority.
- `medium`: intermediate level between `low` and `high`.
- `high`: higher priority, less concurrency.
- `tp`: optimized for transaction processing.
- `tpurgent`: the highest-priority transaction processing level.

In a dedicated deployment (BYOC) every level is allowed regardless of plan: the database is yours. (On Kronbase Cloud the list depends on the plan.) You change it in the dashboard, on the project detail, **Resumen** tab (Overview), under the section shown as «Nivel de servicio de base de datos» (the dashboard is in Spanish). It also works when the project's connection string is a full descriptor: the level of the `service_name` (all of them, if there are several) changes and the host, port and everything else are left untouched. If the string has no recognizable level (for example a SID, or a service without a `_low`, `_medium`, `_high`, `_tp` or `_tpurgent` suffix), the change is rejected without modifying it and the selector shows «Nivel no reconocido».

**Update the instance's API to the current version before using the selector**: earlier versions rewrote full descriptors incorrectly.

The API returns each project's current level in the `serviceLevel` field (`low`, `medium`, `high`, `tp`, `tpurgent`, or `null` if the string has no recognizable level) in the project list, the project detail and the response to the change, together with `connectStringBroken` (`true` if the string carries a `_level` suffix after the last parenthesis left by earlier versions; in that case the selector lets you save the same level to repair it). Both are also included where the connection string is not shown, so the selector reflects the saved level when the page is reloaded.

The change is verified before it is applied: the API opens a test connection with the new level and the project's credentials, with a limit of about 6 seconds. If the connection fails or does not answer in time (for example, because your database does not offer that level), the change is rejected with a 422 `SERVICE_LEVEL_UNAVAILABLE` error, the connection string is not modified and the project keeps its previous level, without cutting its connections. If the database is slow to answer, the selector may take those seconds to show the result. A transient network error also returns 422: if you are sure the level exists, try again.

Only one change per project is checked at a time: if one is already in progress (or a previous test has not finished yet), the request gets 409 `SERVICE_LEVEL_CHANGE_IN_PROGRESS`; wait a few seconds, reload the page and try again if needed. Each API instance runs at most 2 checks at a time across all its projects; if 2 are already running, the response is 503 `SERVICE_LEVEL_CHECK_BUSY` (shown in Spanish: «Hay demasiadas comprobaciones de nivel de servicio en curso. Vuelve a intentarlo en unos segundos.», that is, too many checks in progress, try again in a few seconds). That limit also applies on Kronbase Cloud, where all the platform's customers share it. If many changes are chained in a row, the response is 429 `RATE_LIMITED`. In none of those cases is the string modified.

If the dashboard shows «El despliegue dedicado no respondió a tiempo» (the dedicated deployment did not answer in time), the change may have been applied anyway: reload the page to see the current level before retrying.

`DB_CONNECT_STRING` is the **platform** connection (API keys, projects and metadata), not the connection for each project's data. Every application request starts with that connection, which resolves the API key and the project's credentials on each request (there is no credentials cache); only then is the project's own pool used, with the connection string the project stores. So if `DB_CONNECT_STRING` fails or points to a service that does not exist, no project works (for example, an ORA-12162 error while resolving the key). The level chosen in the selector applies to the project's string, not to `DB_CONNECT_STRING`; the level of the latter affects the requests of all projects and is set with the environment variable. Changing `DB_CONNECT_STRING` is manual and has no automatic rollback: a wrong value leaves the instance without a database, so save the previous value before touching it and check `/health` afterwards. Changing a project's level does not require restarting the API: the project's connections are renewed automatically. For the exact limits of each level and which ones your database type offers, see the Autonomous Database documentation.

### Project quotas

On a dedicated deployment (BYOC) plan limits do not apply: by default each project has **no cap** on storage or on emails per month. Usage is still counted (the dashboard shows it), but it does not block uploads or sends. On Kronbase Cloud quotas are set by the plan and cannot be edited.

To set a cap, use the dashboard: project detail, **Resumen** (overview) tab, «Cuotas del proyecto» (project quotas) card. Each resource (storage and emails per month) has a «Sin límite» (no limit) switch; turn it off, type the cap (storage in MB, from 1 to 5,000,000; emails per month, from 1 to 10,000,000) and press **Guardar cuotas** (save quotas). Turning «Sin límite» back on removes the cap.

- «Sin límite» means that resource has no cap: uploads only depend on the maximum file size and the space in your bucket, and emails on your email service limits (OCI Email Delivery), not on Kronbase.
- With a cap, an upload that would exceed it answers `413`/`429` with `STORAGE_QUOTA_EXCEEDED`, and a send with the quota used up answers `429` `MONTHLY_LIMIT_REACHED` (the quota renews on the 1st of each month, UTC), as on Cloud.
- A cap cannot be set below current usage (storage used or emails sent this month): the API answers `409` `QUOTA_BELOW_USAGE` and changes nothing. Free up space or choose a higher cap.

The equivalent API is `PATCH /platform/customers/me/projects/:id/quotas` (same authentication as the other project routes) with the body `{ "storageMb": number | null, "emailMonthly": number | null }`: `null` removes the cap, an integer sets it and an omitted field is left unchanged. It answers with the updated quotas. On Kronbase Cloud it answers `403` `QUOTAS_NOT_EDITABLE`. The project detail (`GET /platform/customers/me/projects/:id`) includes `quotas` (`storageMb`, `storageUsedMb`, `storageUnlimited`, `emailMonthly`, `emailUsed`, `emailUnlimited`, `editable`); with no limit, `storageMb` or `emailMonthly` is `null`. In the bucket list, `quota` also carries `unlimited`; when it is `true`, `quotaMb` is not a real cap.

**When updating.** Projects created before this version were born with the Free plan quotas (512 MB and 100 emails per month). On BYOC email never had a cap and still does not: only a cap you set from the dashboard limits it. For storage, when the new version starts the API switches to «Sin límite» the projects that still have the default 512 MB; a storage value you changed by hand is kept as a cap (remove it with «Sin límite» if you do not want it). New projects are created with no limit.

**Instances not yet updated.** If you cannot update yet, you can raise the storage cap by hand in your instance database (email already has no cap on BYOC):

```sql
UPDATE PLATFORM_ADMIN.PROJECTS SET STORAGE_QUOTA_MB = <MB> WHERE SLUG = '<slug>';
COMMIT;
```

`PLATFORM_ADMIN` is your instance admin schema: the value of the API variable `PLATFORM_ADMIN_USER` (`PLATFORM_ADMIN` by default). After updating, a value set this way (other than 512) is kept as a cap; to remove it, turn on «Sin límite» in the dashboard. On an instance that is already updated use the dashboard; if you still do it in SQL, also mark the cap as yours, or it is ignored while the project stays «Sin límite»: `UPDATE PLATFORM_ADMIN.PROJECTS SET STORAGE_QUOTA_MB = <MB>, STORAGE_UNLIMITED = 2 WHERE SLUG = '<slug>'; COMMIT;`

**If you go back to an earlier version** (for example, the automatic rollback of a failed update): that version does not know about dashboard caps. It keeps applying the stored storage number (your cap still holds and «Sin límite» still has no cap), but it does not apply an email cap: until you update again, email has no cap.

### Email: domains and sender

The stack automatically passes `OCI_COMPARTMENT_ID` (the stack's `compartment_ocid`) to the API; the Resource Manager form asks no email questions. With the OCI credentials you already provide for Storage plus that compartment, OCI Email Delivery is enabled and the API creates your projects' email domains and their senders there.

To send email you only need to register and verify a domain from the dashboard: the API creates the domain and its DKIM and shows you the DNS records (DKIM, SPF and DMARC) to add, with detection and "Check again", just like on Kronbase Cloud (see [Email](/en/docs/email#domain-dns-records)). The domain goes from `CREATING` to `PENDING` and becomes `VERIFIED` once OCI validates the DKIM; DNS propagation can take a while. With the domain verified, the project sends all its emails from `noreply@yourdomain.com`. Without it, `kb.email().send()` returns `DOMAIN_NOT_VERIFIED` and authentication emails and the test email are not sent (`EMAIL_NO_SENDER`), unless you configure the optional default sender (below). On BYOC / dedicated deployment there is no monthly send cap.

The instance default sender is optional. If you want a fallback sender (for projects without a verified domain and for the instance's own emails, such as alerts to `ADMIN_ALERT_EMAILS`), add the variables `OCI_EMAIL_SENDER`, `OCI_EMAIL_SENDER_NAME` (display name) and, if that sender is approved in a different compartment, `OCI_EMAIL_COMPARTMENT_ID` (it only applies to the default sender; project senders stay in `OCI_COMPARTMENT_ID`) by hand to the `kronbase-api` container. Without a default sender, those alerts are skipped with a log warning. Details in [Email](/en/docs/email#senders).

**IAM permissions.** The API key's user needs to manage Email Delivery in that compartment (confirm this in your tenancy). For example, with a group `kronbase-email` the user belongs to:

```
Allow group kronbase-email to manage email-family in compartment <your-compartment>
```

**Existing instances.** A VM created with an older stack does not receive `OCI_COMPARTMENT_ID`: with OCI credentials but no compartment, email is disabled and the log says so (a local SMTP is never attempted). Add `OCI_COMPARTMENT_ID` (and, if you want, the default sender variables) to the `kronbase-api` container environment and recreate it: remove it with `docker rm -f` and start it again with `docker run --env-file ...`; a `docker restart` does not reread the environment variables. Alternatively, apply the new stack as described in "Existing deployments".

### Updating

You decide when the version changes. When a new version is available, the dashboard shows it next to your deployment and, if your deployment already has the updater, the account owner gets an email for each new version. To apply it, press the update button of the deployment in the dashboard.

What happens when you press it:

1. The updater on your VM pulls the new image from the registry.
2. It replaces the `kronbase-api` container with a new one using the same configuration. While the new one is being checked, the previous one stays stopped as `kronbase-api-pending-prev`; if everything goes well it is renamed to `kronbase-api-prev`.
3. It checks that the new API answers on `/health` (up to 90 seconds by default).
4. If the check fails, it performs an **automatic rollback**: it starts the previous container again and your API stays on the previous version.
5. If the API was updated, it also updates the tunnel (`cloudflared`), as described below.

**The tunnel (`cloudflared`).** After a successful API update, the same order moves the `cloudflared` container to the latest image published by Cloudflare (`cloudflare/cloudflared:latest`); no other image or version can be chosen. If that image is the one already running, nothing is touched. Otherwise it replaces the container with a new one using the same configuration (the current container's, including the tunnel token, which is never shown or logged) and waits up to 60 seconds for the new tunnel to register its connection with Cloudflare (it checks the new container's own logs). Meanwhile the previous one stays stopped as `cloudflared-pending-prev`; if everything goes well it is renamed to `cloudflared-prev`. If the new tunnel does not become ready, **only the tunnel** is rolled back: the previous `cloudflared` comes back and your API stays on the new version. The deployment card shows the outcome of the API update; a tunnel rollback does not change it, but Kronbase administrators are notified. If the latest `cloudflared` image is the one that failed, it will be retried (with its cut) on every update until Cloudflare publishes a fixed one. If the VM has no container named `cloudflared` (custom setups), this step is skipped.

The dashboard reaches your instance through that tunnel (your apps use the private IP and do not depend on it), so the replacement causes a **cut** in the dashboard's contact with the instance: up to about 10 seconds while the previous tunnel stops, plus the time the new one takes to connect. While it lasts, the dashboard loses contact with your instance; your apps' data traffic does not go through the tunnel and is not affected by this cut. The update follow-up tolerates that gap, and the outcome of the API update is recorded before the tunnel is cut. If the new tunnel does not connect, the cut lasts until the previous one is back (up to about 60 more seconds). To avoid it during busy hours, update at a low-traffic time.

The outcome appears on the deployment card in the dashboard:

- **Success:** "Actualizado a la versión …" ("Updated to version …").
- **Failed and rolled back:** "No pudimos actualizar y volvimos a tu versión anterior." ("We could not update and went back to your previous version."), with the reason below. Your deployment keeps serving the previous version; you do not need to do anything for the rollback to happen.
- **Incomplete rollback:** "La actualización falló y no pudimos restaurar tu versión anterior por completo. Tu API podría estar caída: contacta a soporte." ("The update failed and we could not fully restore your previous version. Your API might be down: contact support."), with the details of the failed steps.
- **Not enough disk space:** "No se actualizó: tu instancia no tiene espacio en disco suficiente para descargar la nueva versión. Sigue en la versión anterior. …" ("Not updated: your instance does not have enough disk space to download the new version. It stays on the previous version. …"), with how much space is free and what to do. Nothing was changed; see [Not enough disk space when updating](#not-enough-disk-space-when-updating).
- **Unknown outcome:** "No pudimos confirmar el resultado de la actualización. Revisa la versión mostrada arriba." ("We could not confirm the outcome of the update. Check the version shown above.") It happens if the control plane loses contact with your instance before getting a result; the version your instance reports tells which one is running.

Kronbase administrators are notified when an update ends in a rollback or with an unknown outcome.

If the updater restarts in the middle of an update (for example, because the VM rebooted), on startup it waits for the API to answer: if the new version is healthy it keeps it, otherwise it restores the previous one. The same goes for the tunnel: if it restarted while replacing `cloudflared`, it keeps the new one if it is already connected and otherwise restores the previous one.

**If the tunnel does not come back.** In the rare case that the tunnel is not restored on its own (the dashboard cannot reach your instance after an update), you need a shell on the VM as root (or with `sudo`). The ways in are SSH, if the stack opened port 22 with `admin_cidr_block`, or the OCI instance console connection. The console only works if you set a local password for a VM user beforehand: the Oracle Linux image has none, so without SSH or a password you cannot get in and need to contact support. With a shell, run:

1. Run `docker restart kronbase-updater`: on startup, the updater repairs a half-done tunnel replacement.
2. If it still does not connect, run `docker ps -a --filter name=cloudflared`. If `cloudflared-pending-prev` shows up, run `docker rm -f cloudflared` (if it exists), then `docker start cloudflared-pending-prev` and `docker rename cloudflared-pending-prev cloudflared`. If there is only a stopped `cloudflared`, run `docker start cloudflared`.
3. If none is left, contact support.

**Requirement: the `kronbase-updater` container.** The button only works if the VM runs the updater. It listens only on `172.17.0.1:3100` (the `docker0` gateway, not reachable from outside the VM), uses the deployment's same `control_key`, and needs access to the Docker socket, the registry credentials (the `/root/.docker` directory, after `docker login`) and a state directory of its own (`/var/lib/kronbase-updater`). New stacks start it automatically; its image is set by the `updater_image` variable (default `ghcr.io/kronbase/updater:latest`).

**Existing deployments.** A VM created with an older stack has no updater (and its container is not named `kronbase-api`). To enable it you must replace **only the VM** using the stack you already have in Resource Manager, not create a new one: a new stack would create another ADB and another bucket, both empty. Your data lives in the ADB and Object Storage, not on the VM.

1. In the OCI Console, open in Resource Manager the stack you created the deployment with and edit it (Edit Stack; **not** Create Stack).
2. Upload the new stack zip as the Terraform configuration and check that the variables keep their values (`deployment_id`, `control_key`, tunnel token, credentials).
3. Run a **Plan** and review it before applying anything. The plan must replace only the compute instance (`oci_core_instance`). The Autonomous Database (`oci_database_autonomous_database`) and the bucket (`oci_objectstorage_bucket`) must **not** show up as destroyed or replaced; if they do, do not apply and contact support.
4. If the plan is correct, run **Apply**.

If the plan does not show the instance being replaced (for example, only an in-place update of its metadata, which does not run the VM's initial setup again), its replacement has to be forced: the Terraform equivalent is `terraform apply -replace=oci_core_instance.this`, or marking that resource as "tainted". Depending on the OCI Console version, Resource Manager may not offer that option directly; if you cannot find it, contact support before changing anything. Either way, review the Plan again before applying.

Since the same `deployment_id`, `control_key` and tunnel token values are reused, the deployment stays the same and the tunnel does not change.

**Rolling back across the bucket-policies feature.** A version older than storage policies for user tokens ignores `read` policies, so after a rollback any signed-in user can read files again. Prefer `STORAGE_USER_WRITES_ENABLED=false` (now changed from the [Your instance settings](#your-instance-settings) card) to stop writes with a token and roll back last; details in [Storage](/en/docs#storage).

**Idempotent startup migrations.** Rollback returns to the previous image but **does not revert the database**. For that reason the migrations the API runs on startup are idempotent and backward compatible: the previous version must keep working with the schema the new one left behind.

**Project schema migrations.** After updating, the platform schema changes the new version brings (project columns or privileges) are applied on their own: on the first use of each project and, in the background, with a slow sweep for projects nobody opens. You do not have to run anything. They are always additive and backward compatible, and the updater rollback does not revert them, so the previous version keeps working with the new schema (details and what's new in [Your project's platform schema keeps itself up to date](/en/docs/auth-model#your-projects-platform-schema-keeps-itself-up-to-date)). A change that fails in one project does not prevent the API from starting or that project from being served: it is retried on its own and the administrators receive an email (`ADMIN_ALERT_EMAILS`); the heartbeat also carries to Kronbase a summary with the number of projects with failed changes and, when a schema change failed, the change ids, the error codes and a short masked prefix of the project users; it carries no data from your projects. They are granted by the ADB administrator user (`PLATFORM_ADMIN_USER`), which in BYOC can already do it.

Optional API variables for operators (the defaults are fine; only names and their effect are listed):

| Variable | What for (default) |
|---|---|
| `TENANT_MIGRATIONS_ENABLED` | `false` or `0` turns the migrations and the sweep off, in case they must be stopped in an emergency (`true`) |
| `TENANT_MIGRATIONS_WAIT_MS` | How long the request that opens a project waits at most for its migrations to finish (3000) |
| `TENANT_MIGRATIONS_RETRY_MS` | Wait before retrying a failed change (15 min) |
| `TENANT_MIGRATIONS_BUSY_RETRY_MS` | Wait before retrying if another session was migrating that project (60 s) |
| `TENANT_MIGRATIONS_PASS_TIMEOUT_MS`, `TENANT_MIGRATIONS_CALL_TIMEOUT_MS` | Cap of a whole pass (60 s) and of each database call (30 s) |
| `TENANT_MIGRATIONS_SWEEP_INTERVAL_MS` | How often the background sweep runs (10 min) |
| `TENANT_MIGRATIONS_SWEEP_MAX_PASSES`, `TENANT_MIGRATIONS_SWEEP_MAX_MS` | Maximum projects and time per sweep (200 and 5 min) |

If you prefer to control the version manually, pin a version tag in `docker_image` instead of `latest`: you control which version you get when provisioning.

### Not enough disk space when updating

If the card says your instance does not have enough disk space (the detail, always in Spanish, starts with "Espacio en disco insuficiente", Spanish for "Not enough disk space"), the updater could not download the new version onto the VM disk where Docker stores images. Nothing was changed: your API (or the updater) stays on the previous version.

Before downloading a new version of the API or of the updater, the updater checks that at least 1.5 GiB are free on that disk (not if that version is already downloaded). For the API, if there is not enough it deletes once the old images that no container uses and measures again; for the updater's own update, the request is rejected right away, without deleting anything. If Docker runs out of space in the middle of any download (the tunnel's included), it deletes the old images once and tries again; only if there is still not enough does it reject the order with that message. If it cannot measure the space, it does not block anything. The minimum is set with the `UPDATER_MIN_FREE_BYTES` variable of the `kronbase-updater` container (in bytes; `0` turns the check off); changing it means recreating that container with the new variable.

**Old images.** Each version leaves the previous image on the disk. After every verified update (of the API or of the updater), the updater deletes the old Kronbase images (`api-dataplane`, `updater`) that no container uses anymore, not even a stopped one. It always keeps the image in use and the one of the `-prev` container (the rollback one). It never touches the `cloudflared` image, images of other projects, containers, volumes or networks.

To free space by hand, with a shell on the VM (see "If the tunnel does not come back" in [Updating](#updating) for how to get in):

1. Check the free space with `df -h /` and what Docker uses with `docker system df`.
2. Delete the images no container uses: `docker image prune -a`. It keeps the images of stopped containers, such as `kronbase-api-prev`. Do not use `docker system prune`: it also deletes stopped containers, including the `-prev` ones used to go back and the `-pending-prev` markers the updater uses to finish an interrupted change.
3. If that is still not enough, grow the VM boot volume in the OCI console (the instance, Boot volume, Edit, a larger size). Then, on the VM, run the rescan commands the console shows, if it shows any, and extend the partition and the file system with `sudo /usr/libexec/oci-growfs -y`. Check the result with `df -h /`.
4. Press the update button in the dashboard again.

### Operations from the dashboard

If your VM runs a recent updater, your dedicated deployment page offers several operations that used to require logging into the VM. Each card only shows up if your instance supports it; if one is missing, see [Enable the operations on an existing deployment](#enable-the-operations-on-an-existing-deployment). You do not need to edit files on the VM or recreate containers by hand.

### Your instance settings

The "Ajustes del API" (API settings) card changes a closed set of API settings. No other variable can be set from here.

| Setting | What it controls | Default | Range |
|---|---|---|---|
| `QUERY_BUILDER_DEFAULT_LIMIT` | Rows returned by a query with no explicit limit | 20 | integer from 1 to 50,000 |
| `QUERY_BUILDER_MAX_LIMIT` | Maximum rows a query can ask for | 100 | integer from 1 to 50,000 |
| `RATE_LIMIT_MULTIPLIER` | Factor that multiplies every request rate limit | 1 | 0.1 to 1000, up to 2 decimals |
| `QUERY_EXPRESSIONS_ENABLED` | Expressions in `select` queries | `true` | `true` or `false` |
| `STORAGE_USER_WRITES_ENABLED` | Storage writes with a user token | `true` | `true` or `false` |
| `UPLOAD_MAX_PER_USER` | Simultaneous uploads per user | 2 | integer from 1 to 100 |
| `TENANT_POOL_MAX` | Maximum connections in each project's pool to your ADB | 5 | integer from 4 to 30 |
| `TENANT_POOL_QUEUE_TIMEOUT_MS` | Milliseconds a request waits for a free connection in its project's pool before answering `503` (`DB_POOL_EXHAUSTED`) | 15000 | integer from 1000 to 60000 |
| `PUBLIC_API_URL` | Public URL of your API (`https://your-domain`), used to build the callback URL of each project's sign-in providers (only for providers without an own redirect URI: see the private flow below) | not set | `https://` origin with a domain name, no path, trailing slash, port or credentials |

Rules:

- The default limit cannot exceed the maximum. That relation is checked only when you change one of the two limits, using the values that would result (the new ones, or your instance's current ones for the limit you do not touch). If the result would be inconsistent the change is rejected and nothing is applied; to raise both, change them in the same request.
- Numbers are written in canonical form: no leading zeros, no sign, no spaces and no scientific notation. `RATE_LIMIT_MULTIPLIER` accepts up to 2 decimals and no trailing zeros (`2.5`, not `2.50`).
- You can change between 1 and 9 settings per apply. A setting that is not set on your instance uses the default in the table.
- Changing any of them, the pool settings included, recreates the API container: a cut of about 10 to 15 seconds (see below).

**`PUBLIC_API_URL` and sign-in providers.** Each project's sign-in providers (see [Auth model](/en/docs#auth-model)) need your API's public URL to build the callback URL you register with the provider. New stacks already include it, set to the tunnel hostname, but the tunnel's default rule (`^/platform/`) does not expose the sign-in callback to the internet: on a private deployment use the private flow (below), or knowingly add the optional callback path rule described in the table above. On an existing deployment, set it from this card with the `PUBLIC_API_URL` setting (for example `https://api.your-domain.com`): until then no provider can be enabled, and the dashboard and the CLI warn that it is missing. The setting only appears if your updater supports it; if it does not appear, update the API and the updater first (see [Updating](#updating)). Applying it recreates the container, with the 10 to 15 second cut described below. Provider variables you may have set by hand on the container (`MICROSOFT_*`, `OAUTH_*`) are no longer read.

**Private flow: the API can stay private.** `PUBLIC_API_URL` is only needed for the public browser flow, the one used by providers **without** an own redirect URI. If your API is not exposed to the internet, configure each provider with an **own redirect URI** (a route of your app; dashboard, `kronbase auth provider set --redirect-uri` or `redirectUri` in the API): the provider sends the user back to your app and **your app's backend** forwards `code` and `state` to the API with the project API key (the SDK's `completeOAuthSignIn`, 2.21 or later, or `POST /api/auth/oauth/<slug>/complete`). With an own URI neither `PUBLIC_API_URL` nor the site URL is needed, and the API's public callback is not used. Register in the provider exactly the normalized value Kronbase stores (`https://app.com` is stored as `https://app.com/`). All traffic of that flow comes from your backend's IP: if you need more headroom, raise `RATE_LIMIT_MULTIPLIER` in this same card. Step by step, code example and errors: [Authentication](/en/docs#auth) and [Auth model](/en/docs#auth-model).

**Each project's connection pool.** Every connection in the pool is a session on your Autonomous Database, and the pool is per project: in the worst case your API opens `TENANT_POOL_MAX` × active projects sessions, plus its own (administration, migrations, realtime). They all share your ADB's session limit, which depends on its configuration in OCI: check it before raising the value if you have many active projects. A bigger pool does not make queries faster when the database is already busy either: it only moves the wait from the API to the database. If you see `503` responses with `DB_POOL_EXHAUSTED` on a busy project, raise `TENANT_POOL_MAX` gradually first. Do not lower `TENANT_POOL_QUEUE_TIMEOUT_MS` below the default without a reason: with very low values (for example 1000) short traffic spikes turn into `503` responses, and the same wait applies to the automatic platform schema migrations that run when a project's pool opens, which would fail and be retried later. `TENANT_POOL_MAX` and `TENANT_POOL_QUEUE_TIMEOUT_MS` only appear on the card if your instance supports them; if they do not, update the API and the updater (see [Updating](#updating)).

**Downtime when applying.** To apply the settings, the updater replaces the `kronbase-api` container with a new one with the same image and the new configuration. Your API does not answer for about **10 to 15 seconds**. If the new API does not become healthy, it rolls back automatically to the previous configuration; the card shows the reason. You follow the result from the card itself.

**Reapply.** Kronbase remembers the last settings you applied successfully. If you recreate the VM from the stack (for example, to update the template), the new VM starts with the default values and the card shows that what your instance reports does not match what was applied: press **Reaplicar** (Reapply) to apply your settings again (another cut of 10 to 15 seconds). If your instance no longer supports some of the saved settings (for example, the pool settings after going back to an earlier API or updater version), the rest are reapplied and the card shows which ones were skipped.

### Database password

When you change the password of the `ADMIN` user of your Autonomous Database, the API needs the new one. The "Contraseña de la base de datos" (database password) card, visible only to the account owner, updates it on your instance without logging into the VM. **Order matters:**

1. **First in OCI.** In the OCI console, change the ADB administrator password.
2. **Then in Kronbase.** Type the same password, twice, in the card. Before touching anything, Kronbase tests that the password connects to your ADB; if it does not, it is rejected and your API stays as it was. If it connects, the updater applies it and recreates the API container (a cut of about 10 to 15 seconds).
3. **Finally, update the stack variable.** Edit `adb_admin_password` in Resource Manager with the new password; editing the variable is enough, you do not need to apply the stack. Until you do, the stack keeps the old one: it is out of date, and a VM recreated from that stack would start with a password that no longer works. If you do apply the stack, review the Plan first: applying can recreate the VM (its initial configuration changes and it takes the latest system image), and the new VM would come back with the `ghcr.io` token the stack holds, which may have expired, and with the default settings (see Reapply).

The password must be 12 to 30 printable ASCII characters, with no double quotes, at least one uppercase letter, one lowercase letter and one digit, and without the word `admin` (in any capitalization). Kronbase does not store the password and does not show it afterwards.

**Mind the failed attempts.** The ADB locks the `ADMIN` account after several failed connection attempts, and a lock leaves all your projects without a database. That is why Kronbase limits password changes to **3 submissions every 15 minutes** per deployment, whether they fail or not (one typo and two correct changes already use up the limit). In addition, on your instance the pre-check allows at most 3 failed attempts every 15 minutes: a rejection by the ADB, a timeout (`TIMEOUT`) or a connection error all count as failed. These are Kronbase limits to protect the account; how many attempts your ADB tolerates before locking `ADMIN` is defined by its profile in OCI. If you are unsure which the current password is, do not keep trying: reset it in OCI and start from step 1.

**If applying rolls back.** If the new API does not start with the password, the updater goes back to the previous configuration. In that case the **old password may no longer work** (because you already changed it in OCI) and the API may be left without access to the database, or the `ADMIN` account locked. Reset the `ADMIN` password in OCI (and unlock the account if needed) and try again from the card.

### Control key

The control key is the secret Kronbase uses to talk to your instance. The "Control key" card lets you regenerate it, for example if you suspect it leaked.

1. Press **Regenerar control key** (Regenerate control key) and confirm. Kronbase generates a new key and applies it to your API and the updater. It is an operation with a cut: the API is recreated with the new key (about 10 to 15 seconds) and then the updater is recreated.
2. When it finishes, press **Ver la clave nueva (una sola vez)** (View the new key, one time only) and copy it. It is shown **only once**: Kronbase does not show it again.
3. **Update the `control_key` variable of your stack** in Resource Manager with the new key; editing the variable is enough, you do not need to apply the stack (if you do, review the Plan first: it can recreate the VM). If you do not update it, a VM recreated from the stack would start with the old key.

For 30 minutes your instance also accepts the previous key, but only to read the status, so tracking is not cut in the middle of the change; any change (orders, updates, project management) already requires the new one. After that only the new one works. If you use the CLI with `auth: control-key`, update `KRONBASE_<TARGET>_CONTROL_KEY` with the new key as soon as you regenerate it: with the previous one the CLI stops working immediately. While that window lasts the key cannot be regenerated again.

**Old key warning.** If you recreate the VM from the stack without having updated `control_key`, the VM starts with the retired key. The dashboard detects it and shows a warning that your VM uses an old control key. To fix it, set the stack's `control_key` variable to the key we showed you when you regenerated it and apply the stack again (review the Plan first). If you did not save that key, contact support.

**If the rotation does not complete.** If the operation ends in a rollback and the state of the keys cannot be confirmed, Kronbase **keeps both keys** and tells you on the card (with the text that Kronbase keeps the current and the new control key so as not to lose the connection with your instance). Your deployment keeps working with either of them, so there is no risk of losing access. There is nothing to do on the VM. While the new key stays pending, the other operations keep working and the dashboard lets you retry the regeneration: the same new key is reused, no other one is generated. If the retry does not resolve the state either, contact support.

### Updater

The `kronbase-updater` container is also updated from the dashboard. There are two ways:

- **Automatic, after the API.** When an API update ends well, Kronbase then updates the updater to the same version. The order is always the API first and then the updater. If another operation is in progress at that moment, it waits and retries for a few minutes.
- **With its own button.** The update card shows the updater version and, if the API is up to date and the updater is not, the **Actualizar el actualizador** (Update the updater) button.

The updater cannot replace itself: it launches a helper container (`kronbase-updater-swapper`) that stops the old one, starts the new one and checks that it answers with the expected version. If the new one does not answer within 60 seconds, it restores the previous one. During the change the dashboard loses contact with the updater for a few seconds; this does not affect your API or your apps.

**If it stays "unconfirmed".** The card may say it could not confirm the outcome, or that the new version is running but did not answer the check. First wait a minute or two and reload: the state is reconciled by itself once the updater answers. If it stays the same, run `docker ps -a --filter name=kronbase-updater` and `docker logs kronbase-updater` on the VM:

- If `kronbase-updater` is running, the card should show its version at the next heartbeat (about 5 minutes) and there is nothing else to do.
- If only a stopped `kronbase-updater-pending-prev` exists, restore the previous one: `docker rm -f kronbase-updater` (if it exists and is not running), `docker start kronbase-updater-pending-prev` and `docker rename kronbase-updater-pending-prev kronbase-updater`.
- If no updater container is left, contact support.

### ghcr.io token

Kronbase images are private and the VM pulls them from `ghcr.io` with a read-only token issued by Kronbase (you cannot create your own: the images are private to the Kronbase org and your account has no access). If that token expires, is revoked or loses permissions, pulls fail and you cannot update. The "Credenciales del registro" (registry credentials) card periodically checks your VM's token (the check runs from the VM itself) and warns with "El token de ghcr.io venció o no tiene acceso: solicita uno nuevo a Kronbase" (the ghcr.io token expired or has no access: request a new one from Kronbase). You can force a check with **Comprobar ahora** (Check now), at most once every 5 minutes.

**How to get one.** Kronbase issues the token: it is read-only (`read:packages`) and Kronbase gives it an expiry date. If your VM's token expired, was revoked or lost access, contact Kronbase support and request a new one. Treat it as a secret.

**Paste it in the dashboard.** In the "Credenciales del registro" card, type the user and the token Kronbase gave you under "Actualizar token de ghcr.io". Before saving anything, the updater checks the token against `ghcr.io` with the API and updater images; if it does not work, it is rejected and the previous credentials stay untouched. If it works, it replaces them and there is no cut. The pasted token text is never stored or shown, and the dashboard only keeps the user with parts hidden.

**Warning.** The token is stored on the VM, in the `root` user's Docker credentials. If your host uses a credential store (`credsStore` in the Docker configuration), the host's own `docker` command may ignore that entry, but the updater does use it for its pulls. If you recreate the VM from the stack, it starts again with the token the stack has (`docker_registry_password`): update it there too with the one Kronbase gives you.

### Enable the operations on an existing deployment

A VM created with an older stack runs an updater that does not know how to do these operations (the cards do not show up, or the dashboard says so). There are two ways to enable them:

**Option A: recreate the updater, once.** It does not touch your ADB or the tunnel. An old updater does not include these operations, and the cards only show up when both the API and the updater support them, so do it in this order:

1. **Update the API first** with the usual update button (the old updater already supports it). An old API does not report its operations and, without that, the dashboard offers none even if the updater is new.
2. **Connect to the VM and pull the new updater image before touching the current container.** That way, if the pull fails (for example, because of an expired `ghcr.io` token), your current updater stays up. Replace `<updater_image>` with the updater image (the stack's `updater_image` variable; `ghcr.io/kronbase/updater:latest` by default).
3. **Recreate the updater** with the `CONTROL_KEY` your `kronbase-api` container uses, not the stack's: if you regenerated the key and did not update the stack, the stack's is the retired one. The command reads it into a variable so it is not written in your shell history and, if it does not find it, touches nothing (so you never end up with an updater without a key). Do it when no update is in progress:

```bash
sudo docker pull <updater_image>
CK=$(sudo docker inspect kronbase-api --format '{{range .Config.Env}}{{println .}}{{end}}' | sed -n 's/^CONTROL_KEY=//p')
if [ -z "$CK" ]; then
  echo "The CONTROL_KEY of kronbase-api was not found: the updater was not touched." >&2
else
  sudo mkdir -p /var/lib/kronbase-updater && sudo chmod 700 /var/lib/kronbase-updater
  sudo docker rm -f kronbase-updater
  sudo docker run -d --name kronbase-updater --restart unless-stopped --network host \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v /root/.docker:/root/.docker \
    -v /var/lib/kronbase-updater:/var/lib/kronbase-updater \
    -e CONTROL_KEY="$CK" -e UPDATER_BIND=172.17.0.1 \
    -e UPDATER_STATE_DIR=/var/lib/kronbase-updater \
    <updater_image>
fi
unset CK
```

4. **Wait for the next heartbeat** (up to about 5 minutes): the dashboard then shows the new cards. If they do not show up, check that the API is on the latest version and that `sudo docker ps` shows `kronbase-updater` running.

The difference from the previous command is that the updater now mounts the whole `/root/.docker` directory (not just `config.json`, so it can update the registry token) and a state directory of its own (`/var/lib/kronbase-updater`, with 700 permissions) where it keeps a journal to resume interrupted operations. From then on the updater keeps itself current after every API update, or with **Actualizar el actualizador**.

**Option B: recreate the VM from the stack.** It is the same procedure as "Existing deployments" (in the Updating section, above), with the new stack: the new VM already starts with these mounts.

With these operations, the settings in the table of [Your instance settings](#your-instance-settings) and the ADB password are no longer changed by editing the API container's environment by hand: you do it from the dashboard. The other variables (for example `OCI_COMPARTMENT_ID`, the default sender, `TENANT_MIGRATIONS_*` or `REALTIME_*`) remain stack or container variables, as explained in their sections.

### Limits

- One dedicated deployment per account (registering a second one returns `409`).
- Requires the Enterprise plan.
- File upload from the dashboard is not yet available for projects of a dedicated deployment.
- A `STALE` or `PENDING` deployment does not receive administration operations, because they depend on the tunnel.
- Monitoring and maintaining your ADB and your VM is up to you.


---

# Using Kronbase with AI agents


## Using Kronbase with AI agents

The Kronbase documentation is published in formats designed so a coding agent can read it without scraping HTML. Give it the right URL before asking it to write code against Kronbase.

### Where the machine-readable docs are

| What | English | Español |
|---|---|---|
| Index (`llms.txt`) | `https://kronbase.dev/llms.txt` | `https://kronbase.dev/es/llms.txt` |
| Full documentation as a single text | `https://kronbase.dev/llms-full.txt` | `https://kronbase.dev/es/llms-full.txt` |
| One section as markdown | `https://kronbase.dev/en/docs/<slug>.md` | `https://kronbase.dev/docs/<slug>.md` |

`<slug>` is the section identifier, for example `auth-model`, `transactions`, `plsql` or `realtime`. For most tasks `llms-full.txt` is the most convenient: one read with everything. If the agent has little context, give it the index and let it request only the sections it needs.

### Copy buttons on /docs

On the `/docs` page there are buttons to copy the content and paste it into your agent's chat:

- **Copy all docs for AI** copies the full documentation.
- **Copy section for AI** copies only the section you are reading.

In the Spanish version they are called "Copiar toda la doc para IA" and "Copiar sección para IA".

### Your project's context

The project's Quickstart tab in the dashboard has a button for this. The dashboard is Spanish-only, so it is labeled **"Copiar contexto para IA"**. It copies the project name, the API URL and the tables with their columns, followed by the full Spanish documentation (`/es/llms-full.txt`).

- It never includes API keys: it uses the `<TU_API_KEY>` placeholder, and you put the real key in your own environment.
- For dedicated (BYOC) projects the API URL is the placeholder `<TU_URL_DE_API>`, with a note telling the agent to ask you for your deployment's address.
- When the context is incomplete it says so: the schema or the columns of some table could not be read, or only the first 100 tables are included.
- If the documentation download fails, only the project context is copied and a warning is shown.

### Ready-to-paste prompt

For Claude Code, Codex or another agent:

```text
Before writing code against Kronbase, read https://kronbase.dev/llms-full.txt
and follow that documentation; do not invent endpoints or parameters.

Project rules:
- Install the SDK through the private GitHub Packages registry (@kronbase/client);
  the @kronbase scope is not on public npm.
- Every request to the Data API carries the x-api-key header. With an anon key,
  also add Authorization: Bearer <accessToken> for the user.
- The service_role key is for the backend only: never put it in browser code
  or in NEXT_PUBLIC_* variables.
- POST /api/transaction always requires a Bearer token with an anon key.
- Keys go in environment variables; do not write them in code.

Task: <describe what you need>
```

### Common pitfalls

These are traps that appear in the documentation, useful for reviewing the code an agent writes:

- **`npm install @kronbase/client` fails with 404.** The SDK is a private package on GitHub Packages: you must set `@kronbase:registry=https://npm.pkg.github.com/` and a token in `~/.npmrc` (Installation section).
- **Missing `x-api-key`.** Without it, `401` with `API_KEY_REQUIRED`. The header carries the project key (`anon` or `service_role`); the SDK sends it for you. `anon` keys start with `kb_anon_` and `service_role` keys with `kb_service_` (older ones keep `pk_`); never put a `kb_service_` key in browser code.
- **Bearer token on transactions.** `/api/transaction` has no public-table exception: with an `anon` key it always requires `Authorization: Bearer`.
- **The SDK's `signIn()` returns no tokens.** It returns only `{ success, user }`, and with 2FA it does not hand you the `sessionToken`. To get tokens or sign in with 2FA, call `POST /api/auth/signin` (Auth model section).
- **Real auth routes.** The current user is `GET /api/auth/user`, and refreshing is `POST /api/auth/refresh` with body `{ "refreshToken": "..." }`.
- **PL/SQL calls.** They use `POST /api/query` with `"table": ""`, `operation` `PROCEDURE` or `FUNCTION` and a `plsql` object; they only invoke existing routines owned by the project's schema (not Oracle packages), they do not create them (PL/SQL section).
- **`AUTH_*` tables have restrictions.** The query builder and realtime always reject the auth-internal ones (`AUTH_USERS`, `AUTH_SESSIONS`, `AUTH_REFRESH_TOKENS`, `AUTH_AUDIT_LOG`, `AUTH_OTP_TOKENS`, `AUTH_TOTP_CONFIG`, `AUTH_INVITE_TOKENS`, `AUTH_IDENTITIES`, `AUTH_WEBHOOK_ENDPOINTS`, `AUTH_WEBHOOK_DELIVERIES`) with `AUTH_TABLE_RESTRICTED`. The RBAC ones (`AUTH_ROLES`, `AUTH_PERMISSIONS`, `AUTH_ROLE_PERMISSIONS`, `AUTH_USER_ROLES`, `AUTH_USER_PERMISSIONS`) are allowed only with a `service_role` key (Auth model section).


---

# Webhooks


## Webhooks

Outbound webhooks let Kronbase notify your backend by itself: when something happens in the project (a user signs up, a notification is created...) it sends a signed `POST` request with a JSON body to a URL you chose. Use them for server-to-server integrations: syncing users with your CRM, sending a welcome email from your own system, auditing sign-ins, and so on. Unlike [Realtime](/en/docs#realtime), they need no open WebSocket: your server only has to expose an HTTPS endpoint.

### Quick start

You can also manage them from the **Webhooks** tab of the dashboard (Services group): create endpoints, browse the delivery log and retry failed deliveries.

With the CLI (see [CLI](/en/docs#cli)):

```bash
kronbase webhooks add https://api.acme.com/hooks/kronbase prod \
  --event user.created --event user.deleted --description "CRM sync"
```

The command prints the endpoint `id` and its **signing secret** (`whsec_...`). It is shown only once: store it in your backend's environment. If you lose it, run `kronbase webhooks rotate-secret <id>`.

With the API:

```bash
curl -X POST "https://api.kronbase.dev/platform/customers/me/projects/$PROJECT_ID/webhooks" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{ "url": "https://api.acme.com/hooks/kronbase", "events": ["user.created", "user.deleted"] }'
```

```json
// HTTP 201
{ "endpoint": { "id": "...", "url": "https://api.acme.com/hooks/kronbase", "description": null,
                "events": ["user.created", "user.deleted"], "enabled": true,
                "consecutiveFailures": 0, "disabledReason": null,
                "createdAt": "...", "updatedAt": "..." },
  "secret": "whsec_..." }
```

> **Note:** Platform routes are mounted at the root (`https://api.kronbase.dev/platform/...`), not under `/api`. `$TOKEN` is your account session token (the one `kronbase login` stores), and `$PROJECT_ID` is the project UUID, not the slug. In a dedicated deployment, authenticate with the `x-kronbase-control-key` header instead of `Authorization` (see [CLI](/en/docs#cli)). The easiest route is the CLI, which resolves all of this for you.

Check that your endpoint receives and verifies requests with `kronbase webhooks test <id>`, which sends a `webhook.test` event.

### Events

When creating or editing an endpoint, choose which events it receives (`events`). `*` subscribes to all of them. Every event carries the `id`, `type`, `created_at` and `project_id` fields plus a `data` object with these keys:

| Event | When | `data` |
|---|---|---|
| `user.created` | A user is created (sign-up, OAuth first sign-in, or created by an admin) | `user_id`, `email`, `provider` |
| `user.signed_in` | A user signs in | `user_id`, `email`, `provider` |
| `user.deleted` | An admin deletes a user (`DELETE /api/admin/users/:id`): by default it is deactivated; with `?hard=true` it is permanently removed | `user_id`, `hard` (`false` if it was only deactivated, `true` if it was removed) |
| `user.invited` | An invitation is sent | `user_id`, `email` |
| `user.password_reset_requested` | A password reset is requested for an existing user | `user_id`, `email` |
| `user.mfa_enabled` | A user finishes enabling two-factor authentication | `user_id` |
| `notification.created` | A notification is created with `POST /api/notifications` | `id`, `user_id`, `type` (or `null`), `title` |

`provider` is `password`, `otp`, `magic_link`, `admin` (user created by an admin) or the slug of the OAuth provider (`google`, `microsoft`, ...). In `user.created` through OAuth, `email` can be `null` if the provider does not give one.

**Payloads never carry tokens, links, codes, passwords, secrets or notification bodies.** An event larger than 256 KiB is dropped. The `webhook.test` event (empty `data`) is sent only by `test`, and does not need to be subscribed to.

### Request format

Each delivery is a `POST` with `content-type: application/json` and this body:

```json
{
  "id": "evt_id",
  "type": "user.created",
  "created_at": "2026-12-01T10:00:00.000Z",
  "project_id": "project-uuid",
  "data": { "user_id": "...", "email": "ana@acme.com", "provider": "password" }
}
```

| Header | Content |
|---|---|
| `Kronbase-Event-Id` | Event ID (same as `id` in the body). It is the same in every retry |
| `Kronbase-Event-Type` | Event type (`user.created`, ...) |
| `Kronbase-Delivery-Id` | ID of this delivery to this endpoint |
| `Kronbase-Signature` | `t=<unix seconds>,v1=<hex>` |

`v1` is `HMAC-SHA256(secret, t + "." + body)` in hexadecimal, where `secret` is the endpoint's `whsec_...` string, `t` is the number in the header and `body` is the exact text of the request.

### Verifying the signature

Always verify the signature: anyone who knows your URL could send you a forged request. Verify against the **raw body** (the exact bytes received), not against a re-serialized JSON, and reject old timestamps to prevent replays.

```javascript
import crypto from 'node:crypto'
import express from 'express'

const SECRET = process.env.KRONBASE_WEBHOOK_SECRET // whsec_...
const TOLERANCE_SEC = 300 // 5 minutes

function verify(rawBody, header) {
  let t
  const candidates = []
  for (const part of String(header ?? '').split(',')) {
    const i = part.indexOf('=')
    if (i < 0) continue
    const key = part.slice(0, i).trim()
    const value = part.slice(i + 1).trim()
    if (key === 't') t = value
    else if (key === 'v1') candidates.push(value)
  }
  if (!t || !/^\d+$/.test(t) || candidates.length === 0) return false
  if (Math.abs(Math.floor(Date.now() / 1000) - Number(t)) > TOLERANCE_SEC) return false

  const expected = crypto.createHmac('sha256', SECRET).update(`${t}.${rawBody}`).digest()
  return candidates.some((hex) => {
    if (!/^[0-9a-f]{64}$/i.test(hex)) return false
    const got = Buffer.from(hex, 'hex')
    return got.length === expected.length && crypto.timingSafeEqual(got, expected)
  })
}

const app = express()
app.post('/hooks/kronbase', express.raw({ type: 'application/json' }), (req, res) => {
  const raw = req.body.toString('utf8')
  if (!verify(raw, req.get('Kronbase-Signature'))) return res.sendStatus(400)

  const event = JSON.parse(raw)
  // Idempotency: ignore it if you already processed event.id
  // (Kronbase-Event-Id); then do your work.
  res.sendStatus(200) // any 2xx = delivered
})
```

The header can carry several `v1` values; the request is valid if any matches. Respond within about 5 seconds (after that the attempt counts as failed), and do heavy work after answering.

### Delivery semantics

- **Success** is any `2xx` response. Anything else (another status, a network error, a timeout) is a failed attempt. Redirects (`3xx`) are not followed and count as a failure: register the final URL.
- **At least once.** A delivery can arrive more than once (for example if your server processed it but the response got lost), so deduplicate by `Kronbase-Event-Id` or `Kronbase-Delivery-Id`.
- **Retries.** Up to 6 attempts per delivery: the first one plus 5 retries after 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours. Your endpoint must answer within about 5 seconds; in addition, an absolute 12 second cap covers the whole attempt, including the DNS and address validation. A timed-out attempt counts as failed and is retried following this schedule. After the sixth failure the delivery stays `failed` (you can retry it by hand, see below).
- **Automatic disabling.** An endpoint is disabled after 10 consecutive deliveries that exhaust all their attempts (`disabledReason: "too_many_failures"`), or immediately if it answers `410 Gone` (`"gone"`). `"manual"` is a `disable` by you. When an endpoint is disabled, its pending deliveries become `failed`, and it receives no more events.
- **Re-enabling.** `kronbase webhooks enable <id>` (or `PATCH` with `{ "enabled": true }`) resets the failure counter. Events that happened while it was disabled are **not** replayed.
- **Change propagation.** A change to your endpoints (creating, editing, enabling or disabling, deleting them) can take up to about 30 seconds to apply to events handled by other server instances.
- **No ordering guarantee.** Events can arrive out of order, especially after a retry: use `created_at` if the order matters to you.

### Security and limits

- HTTPS only, on port 443 (the default port; the URL cannot specify another one). No credentials in the URL (`https://user:pass@...`).
- The host must resolve to public IP addresses: `localhost`, private, link-local or internal addresses are rejected. It is checked when creating or editing the endpoint **and** in every attempt.
- Maximum 10 endpoints per project. `url` up to 2048 bytes, `description` up to 500 bytes.
- Events up to 256 KiB.
- Deliveries older than 30 days are deleted automatically while the project keeps processing webhooks or when you list its deliveries.
- The secret (`whsec_...`) is shown once, when creating the endpoint and when rotating it. Rotating with `rotate-secret` invalidates the previous one immediately: update your backend right away.

On a self-hosted or BYOC instance, the operator can change how often the pending deliveries are checked with the `WEBHOOK_WORKER_INTERVAL_MS` environment variable of the API (default 30000).

### Delivery log and retries

Each event sent to an endpoint is a delivery with its history: `status` (`pending`, `success` or `failed`), number of attempts, last HTTP status and last error. The log never includes the event content.

```bash
kronbase webhooks deliveries <id> prod --limit 20 --offset 0
kronbase webhooks retry <id> <deliveryId> prod
```

Retrying only applies to deliveries in `failed` status of an **enabled** endpoint: the delivery goes back to `pending` with its attempts reset, and is sent right away. Otherwise the API answers `404 WEBHOOK_NOT_FOUND`.

### API reference

All routes are under `/platform/customers/me/projects/:id/webhooks` (`:id` is the project UUID) and are authenticated like the rest of the project management routes (see the note in the quick start). Responses are not wrapped in `{ success, data }`.

| Method and path | Body | Response |
|---|---|---|
| `GET /webhooks` | | `200` `{ data: [endpoint] }` |
| `POST /webhooks` | `{ url, events, description? }` | `201` `{ endpoint, secret }` |
| `PATCH /webhooks/:endpointId` | `{ url?, events?, description?, enabled? }` | `200` `{ endpoint }` |
| `DELETE /webhooks/:endpointId` | | `200` `{ ok: true }` (also deletes its log) |
| `POST /webhooks/:endpointId/rotate-secret` | | `200` `{ secret }` |
| `POST /webhooks/:endpointId/test` | | `200` `{ ok, status, error }` |
| `GET /webhooks/:endpointId/deliveries?limit=50&offset=0` | | `200` `{ data: [delivery], limit, offset }` (`limit` 1 to 200) |
| `POST /webhooks/:endpointId/deliveries/:deliveryId/retry` | | `200` `{ ok: true }` |

An `endpoint` has `id`, `url`, `description`, `events`, `enabled`, `consecutiveFailures` (consecutive deliveries that exhausted all their attempts; a success resets it), `disabledReason` (`null`, `manual`, `too_many_failures` or `gone`), `createdAt` and `updatedAt`; it never includes the secret. A `delivery` has `id`, `eventId`, `eventType`, `status`, `attempts`, `nextAttemptAt`, `lastStatusCode`, `lastError`, `createdAt` and `deliveredAt`. In `test`, `ok` is whether your endpoint answered `2xx`, `status` its HTTP code (or `null`) and `error` the reason if it failed.

Errors (the `error` message is in Spanish; rely on `code`):

| Code | HTTP | When |
|---|---|---|
| `INVALID_WEBHOOK_URL` | 400 | Invalid URL, not HTTPS, with credentials or port, or the host is not public |
| `INVALID_WEBHOOK_EVENTS` | 400 | Empty list or an unknown event |
| `WEBHOOK_LIMIT` | 409 | The project already has 10 endpoints |
| `WEBHOOK_NOT_FOUND` | 404 | The endpoint (or delivery, or a retry that does not apply) does not exist |

### CLI

All the commands (`list`, `add`, `remove`, `enable`, `disable`, `rotate-secret`, `test`, `deliveries`, `retry`) are described in [CLI](/en/docs#cli).
