<!-- Generated from apps/site/docs.html by scripts/agent-docs.mjs. Edit the HTML, then rerun it. -->

# Docs

> Build on Haystash DB: Postgres with a data API, sign-in and a JavaScript client. Columns with personal data can be locked, encrypted on the user's device with a key the server never holds.

Haystash DB is Postgres with a data API, sign-in and a JavaScript client, like Supabase or Neon. Columns you mark **locked** are encrypted on the user's device with a key the server never holds, so the database, backups, server and anyone who copies them see only ciphertext. Everything else is ordinary, searchable Postgres you can reach with `psql`. Row-level security, written by the server, decides who reaches which rows.

**Status: a prototype, not audited.** Don't store production data yet. Hosted is invite-only. Full docs: `docs/db/` in the repository.

**AI agents:** use [/llms.txt](/llms.txt), or this page as Markdown at [/docs.md](/docs.md).

## Quickstart

### 1. Get a server

- **[Hosted](/hosted.html):** Haystash runs it. Create a project and copy its address and backend key.
- **[Self-hosted](/self-hosting.html):** run one server beside your own Postgres. `scripts/db-dev.sh` starts both at `http://127.0.0.1:7400` ([how](/self-hosting.html#run)).

Both have the same database, client and console. `URL` below means your server's address.

### 2. Create a table and lock a column

Use the dashboard (hosted), or `http://127.0.0.1:7400/console/` with the admin token (self-hosted).

1. **Tables → Create table**, named `notes`. Keep access **Owner** so users reach only their own rows. Keep the suggested `title` and `body`, with **Lock** ticked on `body`.
2. To lock a column later, press **Lock** on the **Columns** tab, check the dry run (effect on each row, blockers) and type `notes.body` to confirm.

Self-hosted also works through the admin API ([example](/self-hosting.html#run)).

### 3. Read and write from the client

The client isn't on npm yet. Install it from the repository:

```
npm init -y && npm install /path/to/haystash/packages/db
```

```
import { createClient, fileStorage } from '@haystash/db'

const db = await createClient(URL, {      // your server's address
  pinned: ['notes.body'],                  // refuse to run unless notes.body is locked
  storage: fileStorage('./device.json'),   // stay the same device between runs
  persistSession: true,
})

if (!db.auth.user) {
  const up = await db.auth.signUp({ email: 'ada@example.com', password: 'correct horse battery', name: 'Ada' })
  if (up.error) throw new Error(up.error.message)
  console.log('recovery code (show it once):', up.data.recoveryCode)
}

await db.from('notes').insert({ title: 'Monday', body: 'only I can read this' })

const { data, stored } = await db.from('notes').select('title, body').includeStored()
console.log(data.at(-1))     // { title: 'Monday', body: 'only I can read this' }
console.log(stored.at(-1))   // { title: 'Monday', body: 'hs1.k.1._qmrOe7KdCJc5Owt…' }
```

`device.json` is unencrypted (readable only by its owner); keep it out of version control. Browsers can import the client from the server, no build step:

```
<script type="module">
  import { createClient } from 'https://<ref>.<domain>/sdk/db.js'
  const db = await createClient('https://<ref>.<domain>', { pinned: ['notes.body'] })
</script>
```

Allow other origins in Settings, **Allowed app addresses** (hosted), or `HAYSTASH_ORIGINS` (self-hosted). The dev script also serves an example journal at `/journal/`, which needs a table `entries` with `title` and a locked `body`.

### 4. Look at what Postgres stores

`includeStored()` shows it. Locally, you can also query Postgres:

```
$ psql postgres://haystash_server@127.0.0.1:54329/haystash_dev -c "SELECT title, left(body, 40) AS body FROM notes"
 title  |                   body
--------+------------------------------------------
 Monday | hs1.k.1._qmrOe7KdCJc5Owt--yPlRzOD_dboZL4

$ psql … -c "INSERT INTO notes(owner, title, body) VALUES ('someone', 'x', 'plain text')"
ERROR:  new row for relation "notes" violates check constraint "hs_lock_body"
```

Postgres rejects plaintext in a locked column, even from the table's owner role. To stop, press Ctrl-C in `scripts/db-dev.sh`, then run `scripts/pg-dev.sh stop`.

## Concepts

### Locked columns

The device encrypts locked values before sending and decrypts them on read; plaintext never leaves it. Only the row's **owner** can read them, on any of their devices, so these tables need an `owner` column holding a user id.

Locked columns are stored as nullable `text`. Ten types can be locked: `text integer bigint numeric boolean timestamptz date jsonb uuid double precision`. The device checks the type on write and restores it on read.

### Cells: what the database stores

A **cell** is one row's stored value in a locked column:

| Form | Looks like | Made by |
| --- | --- | --- |
| Device | `hs1.k.1.E92QpQnk…` | The owner's device, on every write |
| Sealed | `hs1.s.1.H5asjWDr…` | The server, when locking a column with existing values; only the owner's device opens it |
| Waiting | `hs0."eggs, flour"` | The server, for an owner with no keys yet: marked plaintext, only while a column is locking |

Cells are bound to their project, table, column and owner: moved or changed by one character, they won't open. Devices rewrite Sealed and Waiting cells they read as Device cells. Padding means length shows only a size range, and locked columns take more space.

### The two-part key

Each user's **root key** is made on their device at sign-up and never leaves it in the clear; column keys derive from it. It is stored wrapped under two parts held by different parties: the device secret, recovery code or passkey, **and** a secret held by the **Key Gate** (the server's sign-in and key service). Neither unwraps it alone, so signing in opens no key.

### Devices and recovery codes

| Situation | What happens |
| --- | --- |
| Sign up | The device makes the keys and shows a **recovery code** once. |
| Sign in on a known device | It unlocks with its stored secret and the Key Gate's share. |
| Sign in on a new device | The answer is `new_device`. The user types a code shown on the new device into a signed-in one (**approval**), uses a **passkey**, or enters the **recovery code**. |
| Lost recovery code | A signed-in device makes a new one; the old one stops working. |
| A device is revoked | Its sessions end at once; other devices stay signed in. |
| Lost every device, every passkey and the recovery code | The locked values are gone for good, for you too. |

A **passkey** can replace the recovery code where browsers support it: one fingerprint or face check. It shifts trust to the provider (Apple, Google, a password manager) and works only on your site's address. An optional **Keeper**, off by default, opens a new device's keys with only a Google or Apple sign-in. That is a much weaker promise; read `docs/db/SECURITY.md` first.

### Access modes

Postgres enforces each table's mode through server-written row-level security.

| Mode | Signed-in users | Visitors | Your backend (service key) |
| --- | --- | --- | --- |
| `private` (default) | Nothing | Nothing | Every row |
| `owner` | Read and change only rows whose `owner` is their id | Nothing | Every row |
| `public_read` | Read every row; change only their own | Read every row | Every row |

Tables with a locked column must be `private` or `owner`. `owner` defaults to the signed-in user's id, and users can't change it.

### The signed list of locked columns, and `pinned`

The server keeps a **manifest** of every column ever locked, signed by the Key Gate. Columns only move forward (`locking` → `locked` → `dropped`), and dropped names are retired. Devices remember the highest version and columns they have seen, and stop rather than accept a list that is older, drops a column or moves one backwards. A compromised server therefore can't silently turn a lock off. A device with no history (a new browser, a script without storage) has nothing to compare, so **pin** locked columns in code:

```
const db = await createClient(url, { pinned: ['notes.body'] })
```

Browsers that used a dev server will refuse it after a reset or an old-backup restore. Recovery: [Self-hosting](/self-hosting.html#restore); hosted restores include it.

### What a locked column cannot do

| You cannot | Do instead |
| --- | --- |
| Filter, order, search, join or index on it | Filter on other columns, or on the device after reading |
| Give it a default, a foreign key or a unique constraint | Keep keys and relations in readable columns |
| Lock the primary key or the `owner` column | Lock the other columns |
| Make the table `public_read` | Use `owner` |
| Change a row's owner | Delete the row and insert it again as the new owner |
| Read or write it with the service key | Have the user's device write it; the backend may write `null` |
| Rename or unlock it | Drop the column (its name is retired) |
| Share it with another user | Not built yet |
| Trust it against the server | Treat locked values as confidential, not tamper-proof |

## The JavaScript client

`@haystash/db` runs in browsers and Node 22. Install it from `packages/db` or import it from the server's `/sdk/db.js`. Bundling is safer: the database server can't change code that handles user keys. Calls resolve to `{ data, error }` instead of throwing. Reference: `packages/db/README.md`.

### Connect

```
import { createClient } from '@haystash/db'

const db = await createClient('https://db.example.com', {
  pinned: ['entries.body'],   // refuse to run unless these columns are locked
})
```

### Sign up, sign in, sign out

```
const up = await db.auth.signUp({ email, password, name })
if (up.data?.recoveryCode) showOnce(up.data.recoveryCode)   // even if up.error is set
if (up.error) return showError(up.error)                    // email_taken, …

const r = await db.auth.signIn({ email, password })
if (r.data?.recoveryCode) showOnce(r.data.recoveryCode)     // an imported user's first sign-in
if (r.error) return showError(r.error)                      // invalid_credentials, too_many_attempts, …

await db.auth.signOut()
db.auth.onChange(user => render(user))
```

### A new device, and the recovery code

```
const r = await db.auth.signIn({ email, password })
if (r.data.status === 'new_device') {
  // Either: approval from a device that is already signed in
  const asked = await r.data.requestApproval()
  show(asked.data.code)              // the user types this on the other device
  await asked.data.done
  // Or: the recovery code
  // const rec = await r.data.recover(recoveryCode)
}

// On the signed-in device:
const pending = await db.auth.pendingDevices()
await db.auth.approveDevice(pending.data[0].id, typedCode)

// Replace a lost recovery code (the old one stops working):
await db.auth.newRecoveryCode(password)
```

### Select, insert, update, delete

```
await db.from('entries').insert([{ title: 'Monday', body: 'slept badly' }])

const { data, error } = await db.from('entries')
  .select('id, title, body')
  .order('title', { ascending: false })
  .limit(10)

await db.from('entries').update({ body: 'slept well after all' }).eq('title', 'Monday')
await db.from('entries').delete().eq('title', 'Draft')

await db.from('entries').select().is('body', null)   // error.code 'locked_column': body is locked
await db.from('entries').update({ title: 'x' })      // error.code 'filter_required'
```

Builder methods: `select insert update delete eq neq gt gte lt lte like ilike in is not order limit range single maybeSingle includeStored`. Filters and orders on locked columns are refused before sending.

### What the server stores: `includeStored()`

```
const { data, stored } = await db.from('notes').select('title, body').includeStored()
// data[0].body   === 'only I can read this'
// stored[0].body === 'hs1.k.1.E92QpQnklcSQ…'
```

Use it to show users what a breach would expose.

### Backends: the service client

```
import { createServiceClient, isLocked } from '@haystash/db'

const svc = createServiceClient('https://db.example.com', process.env.HAYSTASH_SERVICE_KEY)
const { data } = await svc.from('entries').select('title, body')
isLocked(data[0].body)                                    // true: the backend sees only the cell
await svc.from('entries').update({ body: 'from the backend' }).eq('title', 'Tuesday')
// error: { code: 'locked_column', status: 403 }
```

The service key reaches every row regardless of access mode, but sees only ciphertext in locked columns and can write only `null` there. Never put it in a browser.

## Your app's own sign-in

Keep your own sign-in (Google, Discord, passwords). After your login check, your backend uses the service key to mint a **ticket**, and the browser passes it to the client. A ticket proves identity only: it works once, for 60 seconds, and opens no key. Keys still come from the device, an approval, a passkey or the recovery code.

### On your backend

```
import { createServiceClient } from '@haystash/db'

const haystash = createServiceClient(process.env.HAYSTASH_URL, process.env.HAYSTASH_SERVICE_KEY)

app.post('/api/haystash-ticket', async (req, res) => {
  const me = req.session.user          // who YOUR session says this is; never an id from the request
  if (!me) return res.status(401).end()
  const { data, error } = await haystash.auth.createTicket({ id: me.id, email: me.email, name: me.name })
  if (error) return res.status(502).json({ code: error.code })
  res.json({ userId: me.id, ticket: data.ticket })
})
```

`id` is your user id (letters, digits, `_` and `-`, up to 64 characters) and becomes the Haystash user id in `owner` columns. `email` and `name` are optional, shown only in the console.

### In the browser

```
const db = await createClient('https://db.example.com', { pinned: ['notes.body'] })

if (!db.auth.user) {                   // a stored session resumes without a ticket
  const { userId, ticket } = await (await fetch('/api/haystash-ticket', { method: 'POST' })).json()
  const r = await db.auth.signInWithTicket({ userId, ticket })
  if (r.data?.recoveryCode) showOnce(r.data.recoveryCode)   // first time: this device made the keys
  if (r.error) return showError(r.error)                    // wrong_user; used or expired: fetch a new ticket
  if (r.data.status === 'new_device') { /* approval, passkey or recovery code, as above */ }
}

// When your app signs the person out:
await db.auth.signOut()
```

### Before you use it

- Anyone with the service key can mint a ticket for any user, act as them on unlocked data, and take over accounts that never signed in. They still can't read locked data. Mint tickets only for the person your session proves.
- `HAYSTASH_PASSWORD_SIGNIN=off` turns off the server's own email-and-password sign-up and sign-in, so tickets are the only way in.
- Move existing users with `haystash import users --external` ([Migrating](#migrating)).

Example: `apps/own-signin`. With `scripts/db-dev.sh` running, start it with `scripts/own-signin-demo.sh`.

## Migrating an existing app

### What fits

A column fits if **only the row's owner reads it** and your server never filters, sorts, searches, joins or processes it. Every row needs an owner who can sign in.

| Fits | Does not fit (in this version) |
| --- | --- |
| A user's private notes, journal, health log, saved addresses, settings only they see | Emails used for sign-in or lookups; anything a backend job, webhook, moderator or admin reads; values two users share (messages); values the server computes; anything you search |

### The steps

```
old database ──read only──▶ haystash import users
                     └────▶ haystash import postgres|mongodb --owner t=col
haystash access t owner
haystash lock t.col --dry-run      (fix blockers, repeat)
haystash lock t.col                (values wait for their owners)
users sign in: keys made, values sealed
purge what is left (optional), then scrub the table
```

The importer (`packages/cli`) only reads the source; use a read-only role. These commands use a self-hosted admin token; hosted projects use a CLI token ([how](/hosted.html#cli)).

```
cd packages/cli && npm install
export HAYSTASH_URL=http://127.0.0.1:7400
export HAYSTASH_ADMIN_TOKEN=$(cat .haystash-db/dev/admin.token)
alias haystash="node $PWD/bin/haystash.js"
```

### Import users

Import users first, so rows get owners the Key Gate knows. With password hashes:

```
haystash import users --from postgres://app@db.internal:5432/app --source accounts \
  --id id --email email --hash password_hash --name display_name --where "deleted_at IS NULL"
```

Accepted: bcrypt up to cost 12; Argon2 (PHC form) up to 64 MiB and 4 passes. A user's first sign-in with their old password **claims** the account: the device makes keys and shows a recovery code. Old second factors aren't checked.

Apps keeping their own sign-in import without hashes and use [tickets](#own-sign-in):

```
haystash import users --from postgres://app@db.internal:5432/app --source accounts \
  --id id --email email --name display_name --external
```

### Import tables

```
# from Postgres (--dry-run first: it creates nothing)
haystash import postgres postgres://app@db.internal:5432/app --tables memos \
  --owner memos=user_id --access owner --skip-unknown-owners

# from MongoDB
haystash import mongodb mongodb://db.internal:27017/shop --collections addresses \
  --owner addresses=userId --access owner --skip-unknown-owners
```

`--owner` copies a column into a new `owner` column. `--skip-unknown-owners` skips rows with unimported owners, which would block every lock. Defaults, indexes, foreign keys, constraints, triggers and views aren't copied. Tables need a single-column primary key.

### Lock, with a dry run first

```
$ haystash lock memos.body --dry-run
Locking memos.body (text)
  4 rows; 1 is empty (NULL) and will stay empty.
  0 values will be sealed right away: their owners have keys.
  3 values will wait for a first sign-in by 2 users (imported, not signed in yet).
No blockers.

$ haystash lock memos.body
```

The dry run changes nothing and lists **blockers** with fixes: no primary key or `owner` column, a `public_read` table, rows without a known owner, an index, default, foreign key or view on the column, an unsupported type, values not storable exactly, or values over 1 MiB.

### Waiting values

Once locking starts, devices encrypt all new values, and values whose owners have keys are sealed within about a minute. Imported users who haven't signed in keep **waiting** cells (readable, marked, counted in the console) until their first sign-in. The column turns `locked` when none remain. Track it in the console or with `haystash status`.

### Purge and scrub

- **Purge** finishes now: it seals what it can and sets remaining waiting values to `NULL`. **Those values are deleted.** It has a dry run and a typed confirmation, in the console and admin API only.
- **Scrub** (recommended) runs `VACUUM (FULL, ANALYZE)` so old plaintext row versions leave the disk. Earlier backups, replicas and logs are untouched; expire them yourself.

There is no unlock. Keep the old database live until the Haystash copy is checked, and rehearse on a copy first.

## The console and keys

Admin console at `/console/`: static files, no build step, light and dark.

| Screen | Shows and does |
| --- | --- |
| Overview | What is locked, waiting values left, users, a getting-started checklist |
| Tables | Create tables; each column's lock state; **Lock** with a dry run, progress, purge and scrub |
| Data | Rows as stored; locked cells as ciphertext |
| Access | The three access modes |
| Users | Users, devices, imported users; suspend, sign out, revoke a device, delete |
| Connect | The URL, the service key (rotate), client and import snippets |

Destructive actions need a typed confirmation; there is no unlock. Hosted projects have these screens in the dashboard, plus Settings, Usage and CLI tokens, and the dashboard holds the admin token for you.

### Admin token

Random, made on first start, stored readable in `admin.token` in the data directory. It has full power over the console and admin API (tables, users, imports, locks, purges, service-key rotation) but **cannot read locked values** and grants nothing on the data API. There is only one; multiple admins aren't built yet.

### Backend key (service key)

Starts with `hsk_` and is shown once, at first start; the server keeps only its hash. Rotate it in **Connect** or with `POST /admin/keys/rotate`; the old key stops working at once.

## HTTP API overview

A hosted project's address answers only `/v1`, `/gate`, `/sdk` and `/health`; its admin API goes through the dashboard.

| Prefix | What | Credential |
| --- | --- | --- |
| `/v1/…` | Data API: rows, schema, the signed list of locked columns, tickets | Session, service key, or none |
| `/gate/v1/…` | Key Gate: sign-up, sign-in, devices, recovery, passkeys | Session |
| `/admin/…`, `/gate/admin/…` | Admin API: tables, columns, locks, purge, scrub, imports, users, keys | Admin token |
| `/console/` | The console | Admin token, pasted in |
| `/sdk/` | The JavaScript client, importable with no build step | None |
| `/health` | `{"ok":true}` | None |

| Credential | Header |
| --- | --- |
| Session | `authorization: Bearer <session>` (the client handles it) |
| Service key | `apikey: hsk_…` |
| Admin token | `x-admin-token: <token>` |

Main data routes: `GET /v1/manifest`, `GET /v1/schema`, `GET`/`POST`/`PATCH`/`DELETE /v1/rows/{table}`, `POST /v1/settle/{table}`, and `POST /v1/auth/ticket` (service key only). Errors are JSON, `{"error": "<code>", "message": "…"}`; branch on `error`. Use the JavaScript client for Key Gate routes; they carry signed, wrapped key material. Full reference: `docs/db/API.md`; exact contract: `docs/db/SPEC.md`.

## Security and limits

### Threat model in brief

| Who | Locked values | Everything else |
| --- | --- | --- |
| Anyone with a database copy or backup | Ciphertext only | Readable: other columns, row ids, owners, timestamps, cell size ranges |
| The database administrator | Can't read or insert plaintext; can delete rows, null cells or swap one user's cells | Readable |
| The server operator | Can't read: the Key Gate holds only one part of each key | Readable, plus emails and passwords sent at sign-in |
| A malicious server | Can't read stored cells; can substitute its own values, withhold rows or serve altered client code | Readable |
| Another user | Can't read or change others' rows | `public_read` rows |
| A network attacker | Nothing behind TLS; everything without it | Same |

The user's device is trusted: malware there sees what the user sees. When hosted, Haystash is the server operator ([what we can and cannot see](/hosted.html#what-we-see)).

### Known limits

- **Not audited:** only two internal AI reviews.
- **No search:** locked columns can't be filtered, sorted, indexed or joined.
- **App code is trusted:** a malicious app update can read what the user unlocks, and a compromised server can serve tampered client code from `/sdk/`. Bundle the client.
- **Not tamper-proof:** the server can't read a value but can replace it.
- **Losing every device, passkey and the recovery code loses the locked values.**
- **Values readable before a lock** may survive in backups, logs, replicas and old database pages. The claim is "unreadable to the server since this date".
- **Waiting values are readable** until first sign-in or purge.
- **Metadata is visible:** row ids, owners, timestamps, unlocked columns, whether a locked value is empty, and its size range.
- **One process, no failover,** shared by the Key Gate and the API.
- **No email verification** at sign-up yet.

Full threat model, guarantees with tests, and all limits: `docs/db/SECURITY.md`. Report problems privately as described in the repository's `SECURITY.md`.

## What's next

Not built yet, roughly in order of need:

- Google or Discord sign-in run by Haystash (today your app runs it and passes a ticket)
- a sealed Keeper in attested hardware
- sharing a locked value with another user (so no private messages yet)
- write-only services: a webhook or backend that adds locked data without reading it
- exact-match lookup on a locked column, e.g. account by email
- a second factor when an imported user claims an account
- separate processes for the Key Gate and the API
- multiple admins with separate permissions
- `purge` and `scrub` in the CLI
- email verification at sign-up
- an external security audit
