Docs

Haystash DB is a Postgres database with a data API, sign-in and a JavaScript client, like Supabase or Neon. You can mark the columns that hold personal data as locked. A locked value is encrypted on the user's own device with a key the server never holds. The database, its backups, the server and anyone who copies them see only ciphertext for that column.

Everything else is ordinary Postgres. You can connect with psql. Other columns stay readable and searchable. Postgres row-level security, written by the server, decides who reaches which rows.

Status: a prototype, not audited. Nobody outside the project has reviewed the code. Do not put production data in it yet. The hosted service is invite-only and not open yet. This page is a short version of the developer docs in docs/db/ in the repository; those pages have every detail.

Using an AI agent? Point it at /llms.txt. This whole page is also plain Markdown in one file at /docs.md.

Quickstart

1. Get a server

Two ways, with the same database, client and console:

Below, URL is your server's address: the project address the dashboard shows when hosted, or http://127.0.0.1:7400 on your machine.

2. Create a table and lock a column

Hosted: open the project in the dashboard. Self-hosted: open http://127.0.0.1:7400/console/ and paste the admin token.

  1. Tables → Create table. Name it notes. Keep access Owner, so each signed-in user reaches only their own rows. The dialog suggests two columns, title and body, with Lock ticked on body.
  2. To lock a column later, press Lock on the table's Columns tab. The console first shows a dry run: what will happen to each row, and anything that blocks the lock. Type notes.body to confirm.

Self-hosted, the same works without the console, with the admin API (example).

3. Read and write from the client

The client is not 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 not encrypted (only its owner can read it). Keep it out of version control. In a browser, import the same client from the server with 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>

A page on another origin must be allowed: in the project's Settings (Allowed app addresses) when hosted, or in HAYSTASH_ORIGINS when self-hosted. The dev script also serves an example app, a private journal, at /journal/. It needs a table entries with title and a locked body.

4. Look at what Postgres stores

includeStored() above already shows it. On your own machine you can also ask Postgres directly:

$ 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 itself refuses plaintext in a locked column, even from the role that owns the table. To stop, press Ctrl-C in the terminal running scripts/db-dev.sh, then run scripts/pg-dev.sh stop.

Concepts

Locked columns

A table is ordinary Postgres. Any column whose values are personal can be locked. From then on:

A locked column is stored as text and is always nullable. Ten types can be locked: text integer bigint numeric boolean timestamptz date jsonb uuid double precision. The device checks the type before writing and returns the right JavaScript type when reading.

Cells: what the database stores

The text stored in a locked column for one row is a cell. It has one of three forms:

FormLooks likeMade by
Devicehs1.k.1.E92QpQnk…The owner's device, on every write
Sealedhs1.s.1.H5asjWDr…The server, while locking a column that already had values. Only the owner's device can open it.
Waitinghs0."eggs, flour"The server, for a value whose owner has no keys yet. It is still plaintext, marked. It exists only while a column is locking.

A cell is bound to its project, table, column and owner. Copied into another row, or changed by one character, it does not open. When a device reads a Sealed or Waiting cell, it re-encrypts it as a Device cell in the background. Values are padded, so a cell's length shows only a size range. Locked columns take more space than the values they hold.

The two-part key

Each user has a root key, made on their device at sign-up. Every column key is derived from it on the device; it never leaves the device in the clear. The root key is stored only wrapped under two parts held by different parties:

Neither the Key Gate nor a device alone can unwrap it. Signing in says who the person is; it does not open a key by itself.

Devices and recovery codes

SituationWhat happens
Sign upThe device makes the keys. The user gets a recovery code, shown once.
Sign in on a device used beforeThe device unlocks with its stored secret and the Key Gate's share.
Sign in on a new deviceThe answer is new_device. The user types a code shown on the new device into a device that is already signed in (approval), uses their passkey, or enters the recovery code.
Lost recovery codeA signed-in device makes a new one. The old one stops working.
A device is revokedIts sessions end at once. The user's other devices stay signed in.
Lost every device, every passkey and the recovery codeThe locked values are gone. Nobody, including you, can get them back.

A passkey can replace the recovery code where the browser supports it: one fingerprint or face check on a new device, nothing to write down. It moves trust to the passkey provider (Apple, Google, a password manager) and works only on your site's own address. An optional, off-by-default Keeper service lets a new device open the keys with a Google or Apple sign-in alone. It is a much weaker promise; read docs/db/SECURITY.md in the repository before turning it on.

Access modes

Each table has one of three modes. Postgres enforces them with row-level security policies the server writes.

ModeSigned-in usersVisitorsYour backend (service key)
private (default)NothingNothingEvery row
ownerRead and change only rows whose owner is their idNothingEvery row
public_readRead every row; change only their ownRead every rowEvery row

A table with a locked column must be private or owner. The owner column defaults to the signed-in user's id, and a user cannot change it.

The signed list of locked columns, and pinned

The server keeps a manifest: the list of every column that is locked, or ever was. The Key Gate signs it. A column only moves forward (locking → locked → dropped), and a dropped column's name can never be used again.

Every device remembers the highest version it has seen and every column on it. It stops working rather than accept a list that is older, drops a column, or moves one backwards. This stops a compromised server from quietly turning a lock off and receiving plaintext. A device that has never seen the list (a new browser, a script with no storage) has nothing to compare with, so apps should pin their locked columns in code:

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

One side effect: resetting a development server, or restoring an old backup, makes browsers that used it refuse it. That is the protection working. Self-hosting says how to recover after a restore; on a hosted project, we do it as part of the restore.

What a locked column cannot do

You cannotDo instead
Filter, order, search, join or index on itFilter on other columns, or on the device after reading
Give it a default, a foreign key or a unique constraintKeep keys and relations in readable columns
Lock the primary key or the owner columnLock the other columns
Make the table public_readUse owner
Change a row's ownerDelete the row and insert it again as the new owner
Read it, or write a value, with the service keyHave the user's device write it; the backend may write null
Rename or unlock itDrop the column (its name is retired)
Share it with another userNot built yet
Trust it against the serverTreat locked values as confidential, not tamper-proof

The JavaScript client

@haystash/db works in browsers and Node 22. Install it from the repository (packages/db), or import it in a browser from the server's /sdk/db.js. Bundling it with your app is safer: then the database server cannot change the code that runs with the user's keys. Every call resolves to { data, error } and does not throw for a server error. The full reference is packages/db/README.md in the repository.

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. A filter or an order on a locked column is refused before the request is sent.

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 of every table, whatever the access mode. For locked columns it sees only ciphertext, and it can write only null to them. Keep it on your server, never in a browser.

Your app's own sign-in

If your app already signs people in (Google, Discord, or passwords it checks itself), it can keep doing so. After your own login check, your backend asks Haystash for a ticket for that person, using the service key. The browser hands the ticket to the client. A ticket says only who the person is: 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 own user id (letters, digits, _ and -, up to 64 characters). It becomes the Haystash user id, the value in owner columns. email and name are optional and only shown 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

apps/own-signin in the repository is a small working example. 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 ever needs to read it, and your server never needs to filter, sort, search, join or process it. Each row needs an owner who can sign in to Haystash.

FitsDoes not fit (in this version)
A user's private notes, journal, health log, saved addresses, settings only they seeEmails 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 is packages/cli in the repository. It only reads your source database. Use a source role that can only read.

The commands below are for a self-hosted server, with its admin token. A hosted project uses a CLI token instead (how).

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 the rows you import next have owners the Key Gate knows. With their 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 hashes: bcrypt up to cost 12, and Argon2 in PHC form up to 64 MiB and 4 passes. An imported user's first sign-in with their old password claims the account: the device makes their keys and they get a recovery code. A second factor from the old system is not checked at claim.

If your app keeps its own sign-in, import users without hashes and sign them in with tickets:

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 the given column into a new owner column. --skip-unknown-owners leaves out rows whose owner was not imported, because such rows would block every lock. Defaults, indexes, foreign keys, constraints, triggers and views are not 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. It lists any blockers with a fix: 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 that cannot be stored exactly, or values over 1 MiB.

Waiting values

Once the lock starts, every device encrypts new values. Values whose owner has keys are sealed within about a minute. Values of imported users who have not signed in yet stay as waiting cells: still readable in the database, marked, and counted in the console. Each is sealed after that user's first sign-in. The column becomes locked when none are left. Follow progress in the console or with haystash status.

Purge and scrub

There is no unlock. Keep the old database serving the app until the Haystash copy is checked, and try the whole procedure on a copy first.

The console and keys

The server serves an admin console at /console/. It is static files with no build step, in light and dark.

ScreenShows and does
OverviewWhat is locked, waiting values left, users, a getting-started checklist
TablesCreate tables; each column's lock state; Lock with a dry run, progress, purge and scrub
Data"What the database holds": rows exactly as stored, locked cells shown as ciphertext
AccessThe three access modes
UsersUsers, devices, imported users; suspend, sign out, revoke a device, delete
ConnectThe URL, the service key (rotate), client and import snippets

Destructive actions need a typed confirmation. The console never offers "unlock".

On a hosted project the same screens are in the dashboard, with Settings, Usage and CLI tokens beside them. You never see the admin token there; the dashboard acts for you.

Admin token

A random token the server makes on its first start, stored readable in admin.token in the data directory. It runs the console and the admin API, and has full power: it creates and deletes tables and users, imports, locks, purges and rotates the service key. It cannot read locked values, and it grants nothing on the data API. There is one admin token; more admins with separate permissions are not built yet.

Backend key (service key)

Starts with hsk_. It is shown once, at the first start, and the server keeps only its hash. Copy it then, or rotate it later in the console (Connect) or with POST /admin/keys/rotate; the old key stops working at once. It reaches every row, but sees only ciphertext in locked columns.

HTTP API overview

One server, several prefixes. A hosted project's address answers only /v1, /gate, /sdk and /health; its admin API is reached through the dashboard.

PrefixWhatCredential
/v1/…Data API: rows, schema, the signed list of locked columns, ticketsSession, service key, or none
/gate/v1/…Key Gate: sign-up, sign-in, devices, recovery, passkeysSession
/admin/…, /gate/admin/…Admin API: tables, columns, locks, purge, scrub, imports, users, keysAdmin token
/console/The consoleAdmin token, pasted in
/sdk/The JavaScript client, importable with no build stepNone
/health{"ok":true}None
CredentialHeader
Sessionauthorization: Bearer <session> (the client handles it)
Service keyapikey: hsk_…
Admin tokenx-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. The Key Gate routes carry signed and wrapped key material, so use the JavaScript client rather than calling them by hand.

The full reference, with filters, limits, every route and every error code, is docs/db/API.md in the repository. The exact contract is docs/db/SPEC.md.

Security and limits

A locked column's values are encrypted on the owner's device under a key derived from their root key, which the server never holds. The database, its backups, the server and its operator see ciphertext for those columns. Postgres refuses plaintext in a locked column. Devices check the signed list of locked columns, so a compromised database or server cannot quietly switch a lock off for a device that has seen it, or for an app that pins its columns.

Threat model in brief

WhoLocked valuesEverything else
Someone with a copy of the database or a backupCiphertext onlyReadable: other columns, row ids, owners, timestamps, each cell's size range
The database administratorCannot read them or insert plaintext. Can delete rows, set cells to NULL or swap one user's cells.Readable
The server operatorCannot read them: the Key Gate holds only one part of each keyReadable, plus every user's email and the passwords sent at sign-in
A malicious serverCannot read stored cells. Can replace a locked value with one of its own, withhold rows, or serve altered client code.Readable
Another userCannot read or change other users' rowsRows of public_read tables
A network attackerNothing with TLS in front; everything without itAs for locked values

The user's device is trusted: malware there sees what the user sees.

When Haystash hosts your project, Haystash is the server operator in this table. What we can and cannot see says it plainly.

The honest limits

The full threat model, each guarantee with its test, and all known limits are in docs/db/SECURITY.md in the repository. Report problems privately, as described in the repository's SECURITY.md.

What's next

Not built yet, roughly in the order a real app needs them: