scribase-cli/README.md
caelum0x a079b89d2d feat(SCR-ACT): init makes the first request itself and returns the rows (0.3.10)
scribase init / init --temp now reads the sample todos table through the
project's REST API with the public key as soon as the backend is ready,
prints the rows and returns them as first_request in --json. Agent-created
projects count as activated without a human click. A failed read never
fails init; the curl stays as the first next step in that case.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 21:02:39 +03:00

347 lines
17 KiB
Markdown

# scribase
![scribase env create, then scribase env get showing phase: ready](https://assets.scribase.com/clips/scribase-loop-6s-readme-20261117.gif)
`npx scribase init` gives a coding agent a live backend — Postgres, Auth,
Storage — with zero human signup (`--temp`: a 72-hour project, no form, no
card). Every new table is row-level-security required by default:
`scribase migrate` blocks a `public`-schema table with no RLS policy before
anything runs. A destructive push to a production environment from a
non-admin agent token waits for the project's named human approver to say
yes before it executes, instead of running unattended. Toolgate, the sibling
agent-tool gateway, runs on the same model: one key, each tool's price shown
and held before it runs, spend caps enforced server-side.
This repo is the `npx scribase` CLI and the typed, fetch-based TypeScript
client for the [Scribase](https://scribase.com?ref=npm) management `/v1` API, both
shipped as the single `scribase` npm package. It talks to the same public
`https://api.scribase.com` endpoint the dashboard and console use — nothing
in this repo runs a database or a control plane itself. It also works with
`@supabase/supabase-js`: `init` writes the same env var names and installs
that client, so your generated code and REST calls are compatible with
Supabase's.
- **Zero runtime dependencies.** A thin, typed wrapper over `fetch`.
- **Contract-first core.** `src/types.gen.ts` is emitted from
`api/openapi.yaml` (orgs, memberships, projects, environments, operations,
audit, imports, migrations, exports). Newer surfaces (backups, restores,
usage, database, queues, functions, account, …) are typed by hand in
`src/resources/*.ts` against the exact bodies `crates/control-api` renders;
each type's doc comment names the server function it mirrors.
- **Async-operation aware.** Every mutation returns an `Operation` to poll, and
the client gives you `wait(...)` helpers so "accepted" becomes "done".
- **Idempotency + retries built in.** Mutating calls attach an
`Idempotency-Key` automatically; 429/503/network failures back off and retry.
Requires Node >= 22.13 (built-in `fetch`, `crypto.randomUUID`) or any runtime
with the Fetch and Web Crypto globals.
## `npx scribase init`
The package also ships a `scribase` binary, made for coding agents (Claude
Code, Codex, Cursor, Windsurf) and people alike:
```bash
npx scribase init --json # not signed in: a 72-hour temporary project with a claim link
# signed in (SCRIBASE_ACCESS_TOKEN or `scribase login`): your account
npx scribase init --account # not signed in, but use an account (approve in the browser)
npx scribase init --watch # also wait for the app's first request
npx scribase sql "create table notes (id bigint generated always as identity primary key, body text)"
# run SQL on this folder's project, in one transaction
npx scribase doctor # check env vars, keys and the connection; one fix per problem
```
A new project comes with a small sample `todos` table (row level security on,
read-only for the public key), and init makes the first request itself: it
reads that table through the project's REST API with the public key
(`GET /rest/v1/todos?select=*`), prints the rows, and puts them in the
`--json` output as `first_request` (`ok`, `status`, `row_count`, `rows`). No
curl to paste, no browser: when init exits, the backend has already answered
a real query. The next steps then query it with `supabase.from('todos')` and
create a table of your own with `npx scribase sql`. If the read did not work
(`first_request.ok` is false), the project is still live and the first next
step is the `curl` that repeats it.
`sql` holds back statements that remove data until you add `--confirm`.
```sh
npx scribase env # this project's environments; * marks this folder's
npx scribase branch create add-comments # a copy-on-write database with its own URL and keys
npx scribase branch # list branches
npx scribase branch delete add-comments --yes
```
These commands act on this folder's project, so the token `init` wrote to the
env file here wins over an exported `SCRIBASE_ACCESS_TOKEN`, and that over
`scribase login`. If the two differ, one line says which was used
(`SCRIBASE_TOKEN_SOURCE=shell` uses the exported one); `--verbose` always
prints the token's source, never the token.
Init prints "Live in N s" with the measured time. The claim link carries
`?ref=<install id>`, a random id stored in `~/.config/scribase/install-id`
(`SCRIBASE_NO_REF=1` sends none). Claiming is a sign-up: free for 14 days, no card, and one
project stays free after that. The URL and keys stay the same.
It detects Next.js, Expo, Vite or plain Node, creates (or reuses) a project,
writes the env file with that framework's variable names
(`NEXT_PUBLIC_SUPABASE_URL`, `EXPO_PUBLIC_SUPABASE_URL`, `VITE_SUPABASE_URL`,
`SUPABASE_URL`, and the anon key; the service-role key only where it cannot
reach a client bundle), installs `@supabase/supabase-js`, writes a small
client module and prints one JSON object (`ok`, `api_url`, `env_vars`,
`client_file`, `claim_url`, `next_steps`, or `ok: false` with an error `code`
and a `next` step). Run it again and it reuses the same project.
When the folder is linked to Vercel (`.vercel/project.json` or
`VERCEL_PROJECT_ID`), init also sets the URL and keys on that Vercel project for
development, preview and production, using `VERCEL_TOKEN` or the signed-in
`vercel` CLI, and reports `vercel: { status, targets }` (`updated`,
`not_linked`, `no_credentials`, `failed`). It never fails init; `--no-vercel`
turns it off.
## `npx scribase migrate`
Tracked, repeatable SQL migrations in `supabase/migrations/*.sql`:
```bash
npx scribase migrate new add_notes # scaffold supabase/migrations/<version>_add_notes.sql
npx scribase migrate # send every local file, oldest first; plan, lint, apply
npx scribase migrate --dry-run # plan and lint only; nothing runs
npx scribase migrate rollback # revert the most recently applied migration
npx scribase migrate rollback 2 # revert the last 2 applied migrations
npx scribase migrate rollback --dry-run # preview a rollback; nothing written or applied
```
Re-running `migrate` is always safe: already-applied files are skipped, and a
changed already-applied file aborts the whole run (checksum drift) rather
than silently diverging. A `public`-schema table with no row-level security
policy is blocked before anything executes (`missing_rls`), same as every
other lint rule (`permissive_policy`, `no_with_check`, `security_definer`,
`public_grant`).
`rollback` reverts the `n` most recently applied migrations (default 1) by
running their stored `-- down` SQL — the optional second half of a migration
file, after a `-- down` marker:
```sql
create table public.notes (id bigint generated always as identity primary key, body text);
alter table public.notes enable row level security;
create policy notes_select_own on public.notes for select using (auth.uid() is not null);
-- down
drop table public.notes;
```
There is no separate server route that deletes a ledger row over the
network, so `rollback` writes the down SQL to disk as a brand new, ordinary
migration file (`<new version>_rollback_<name>.sql`) and sends it through
the exact same `POST .../migrations` route — and the exact same
destructive-push production-approval gate — any other migration already
goes through. A rollback is itself a tracked migration, not a special path
that bypasses either; every other environment that later runs `migrate`
replays the same rollback. Refused with a clear error when the target
migration has no down SQL, or when asked to roll back more than are
applied.
## `npx scribase add email`: transactional email
```bash
npx scribase add email --json # sign-in email for this project, one proof to your account address
npx scribase add mail --json # product email (Resend-shaped API), same proof
npx scribase add --list # every other capability (push, storage-s3, errors, ...), same pattern
```
`add email` turns on the project's sign-in email (magic links, one-time
codes, password resets) and proves it with one real send to the signed-in
account's own address. `npx scribase add mail` does the same for product
email your app sends itself (receipts, invites) through a Resend-shaped API
([docs](https://docs.scribase.com/docs/api/app-mail.md)).
What needs an account and what does not:
- **Database, auth, storage, REST: no account.** `npx scribase init --temp --json`
gives a live 72-hour project with nobody signing up.
- **Email: the project has to be claimed first.** An unclaimed temporary
project is not allowed to send mail to arbitrary addresses (it would be an
open relay), so `add email --to <address>` on it answers
`email_recipient_refused` (HTTP 403). Claiming is one click on the
`claim_url` that `init` printed and saved in `.scribase/project.json`: sign
up, free for 14 days, no card, same URL and keys. After that `add email`
works and the app can send.
## Install
```bash
npm install scribase
# or
pnpm add scribase
```
Working on this repository directly? Clone it and build from source instead:
```bash
git clone https://git.ereboslab.com/caelum0x/scribase-cli.git
cd scribase-cli
npm install
npm run build
npx ./dist/cli/index.js --help # or: npm link, then `scribase --help`
npm install file:../path/to/scribase-cli # in your app, instead of the npm registry
```
## Quick start
```ts
import { ScribaseClient } from 'scribase';
const scribase = new ScribaseClient({
baseUrl: 'https://api.scribase.com', // your installation's management endpoint
token: process.env.SCRIBASE_ACCESS_TOKEN ?? '',
});
// Bootstrap an org (idempotent; caller becomes owner), then a project.
await scribase.organizations.put('acme', { display_name: 'Acme, Inc.' });
await scribase.projects.put('acme', 'store', { region: 'us-east', postgres_major: 17 });
// Provision production. Mutations are asynchronous.
const { operation } = await scribase.environments.create({
organization_id: 'acme',
project_id: 'store',
environment_id: 'production',
kind: 'production',
data_mode: 'snapshot',
region: 'us-east',
postgres_major: 17,
});
await scribase.operations.wait(operation.id, 'acme', {
onUpdate: (op) => console.info(`provision: ${op.state}`),
});
```
## Resources
Every method maps to one real route in `crates/control-api/src/http.rs`.
| Accessor | Methods → endpoints |
|---|---|
| `client.organizations` | `put`/`get` `/v1/organizations/{id}`, `update` (`PATCH`, rename), `list` `/v1/organizations`, `putMembership`/`listMemberships` `…/memberships`, `scheduleDeletion` (`DELETE`), `get`/`putNotificationSettings`, `listApiKeys`/`createApiKey`/`revokeApiKey` `…/api-keys`, `listPolicies`, `listMcpTools` |
| `client.projects` | `put`/`get` `…/projects/{id}`, `list` `…/projects`, `listDomains` `…/domains` |
| `client.environments` | `list`/`create` `/v1/environments`, `get`/`delete` `…/{env}`, `suspend`/`resume`/`renew`, `connection` (server-side only), `logs` |
| `client.previews` | built on environments: `create`/`list`/`get`/`delete`/`renew` — TTL-swept, `sanitized` by default |
| `client.backups` | `list`/`create` `…/environments/{env}/backups`, `get` `…/projects/{p}/backups/{id}?environment=`, `verify` `…/environments/{env}/backups/{id}/verify`, `restore` `…/backups/{id}/restore` |
| `client.restores` | `start` — restore-shaped form of `backups.restore`; `list`/`get` `…/environments/{env}/restores[/{id}]`, `waitForCompletion` |
| `client.export` | `create` `…/environments/{env}/exports`, `createForProject` `…/projects/{p}/export`, `list` `…/projects/{p}/exports`, `getManifest` `…/exports/{id}`, `downloadUrl`/`download` (signed `…/exports/{id}/download`) |
| `client.migrations` | `run` `…/migrations` — plan → lint → apply |
| `client.imports` | `create`/`dryRun` `/v1/imports`, `history`/`report` `…/imports` |
| `client.usage` | `get` `…/environments/{env}/usage`, `capsNearingLimit`, `billing` `…/organizations/{org}/billing` |
| `client.database` | `tables` `…/database/tables`, `query` `…/database/query` (read-only) |
| `client.queues` | `list`, `peek`, `create`/`send`/`read`/`archive`/`delete`/`purge` |
| `client.functions` | `list`, `deploy`, `invoke` |
| `client.auth` | `listUsers`, `listProviders`, `listPolicies` |
| `client.storage` / `client.realtime` / `client.metrics` / `client.insights` | read surfaces for the console |
| `client.branches` | `list`/`register`/`diff`/`merge`/`linkPullRequest` |
| `client.account` | `get`/`update` (`PATCH`) `/v1/account`, `security`, `revokeSession`/`removeFactor`, `enrollFactor`/`verifyFactor` (TOTP), `challenge` (MFA step-up), `listTokens`/`createToken`/`revokeToken` |
| `client.operations` | `get` `/v1/operations/{id}`, `wait` |
| `client.audit` | `list`, `paginate` over `…/audit-events` |
## The two money surfaces
**Verified restore.** Backups become restorable only once the backup worker has
verified them (`status: 'available'`); the control plane refuses anything else.
A restore always lands in a *different* environment, and the finished record
carries its own evidence: relation count, RLS relation count, and the SHA-256
of the evidence document.
```ts
import { isRestorable, restoreEvidence } from 'scribase';
const production = { organizationId: 'acme', projectId: 'store', environmentId: 'production' };
const [latest] = (await scribase.backups.list(production)).filter(isRestorable);
if (latest) {
// Restore into a scratch preview, never over production, to prove the backup.
const { restore } = await scribase.backups.restore(production, latest.backup_id, 'restore-check');
console.info(restore.id, restore.status); // 'pending' until the restore worker finishes
const proof = restoreEvidence(restore); // non-null once status === 'restored'
}
```
**Runnable export.** No lock-in: assemble a complete, runnable stack with a
signed manifest. The call is synchronous and returns the manifest directly.
```ts
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'production' };
const { manifest, bundleRef } = await scribase.export.create(ref, { format: 'compose' });
// `manifest.artifacts[]` carries per-file sha256; `manifest.signature` signs the
// manifest; `bundleRef` is where the control plane wrote the bundle.
```
## Migrate an existing project
The dry-run is the sales tool: it prints exactly what will move and what won't,
before anything is written. Acceptance is binding — existing users log in
afterward *without resetting passwords*.
```ts
const source = {
source: 'supabase' as const,
sourceProjectRef: 'abcdefgh',
sourceConnectionString: process.env.SOURCE_DB_URL ?? '',
sourceServiceKey: process.env.SOURCE_SERVICE_KEY ?? '', // sent once, never logged
destination: { organizationId: 'acme', projectId: 'store', environmentId: 'production' },
};
const plan = await scribase.imports.dryRun(source); // nothing is written
const report = await scribase.imports.run(source); // starts it in the background, follows progress, returns the verified report
// or: const job = await scribase.imports.createFrom(source); then scribase.imports.progress(job.import_id)
```
## Apply migrations safely
`plan → lint → apply`. A blocking lint finding (`missing_rls`, `public_grant`,
`permissive_policy`, `no_with_check`, `security_definer`) refuses the migration
before a single statement runs.
```ts
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'production' };
const result = await scribase.migrations.run(ref, {
migrations: [{ version: '20260921120000', name: 'add_notes', up: 'create table ...' }],
apply: true,
});
// result.plan, result.lintFindings, result.applied
```
## Pagination
```ts
for await (const event of scribase.audit.paginate('acme', { limit: 200 })) {
console.info(event.sequence, event.action);
}
```
## Errors
Every failure is a typed subclass of `ScribaseError`. API errors carry the
parsed RFC 9457 `problem+json` body:
```ts
import { ConflictError, QuotaExceededError } from 'scribase';
try {
await scribase.environments.create(spec);
} catch (error) {
if (error instanceof QuotaExceededError) {
// buy a capacity pack; retry after error.retryAfterSeconds
} else if (error instanceof ConflictError) {
console.error(error.problem.code, error.requestId);
}
}
```
## Regenerating types
`src/types.gen.ts` is generated; never edit it by hand. `scripts/generate.ts`
reads the `api/openapi.yaml` contract from Scribase's main (private) repo, so
regenerating it is a Scribase-team-only step — it is not needed to build,
test or use this package, since `types.gen.ts` already ships checked in.
## License
Apache-2.0.