npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@aiquants/vault-drizzle

v0.6.0

Published

SQL Server storage for @aiquants/vault-core on drizzle (node-mssql): vault tables, fenced transactions, application locks, DDL and grants.

Readme

@aiquants/vault-drizzle

The SQL Server storage of @aiquants/vault-core on drizzle (node-mssql): the vault's tables, fenced transactions under application locks, and the DDL and grants that create them.

  • Fenced transactions: every transaction takes the vault's keyring lock (sp_getapplock) as its first statement, shared to read and write items and exclusive to advance the seal epoch or run a ceremony, and then compares the stored key version and seal epoch with the ones the vault opened it for. A mismatch refuses with VaultKeyStateChangedError before any work runs. A writer reads its item with an update lock, so two writers of one item run one after the other.
  • Ceremony lock: a key ceremony holds a session-owned lock on a dedicated connection for its whole length, and each of its transactions checks it still holds that lock before it commits (a dropped connection loses the lock; the transaction then rolls back with VaultBusyError lock-lost).
  • Exact columns: binary values are written from their hexadecimal text through convert, instants through @aiquants/mssql/drizzle's exactDatetimeOffset (their UTC text, converted in SQL) into datetimeoffset(3), and secret IDs and compartment codes compare with a binary collation. Reads check every value's shape and refuse a row that cannot be what the vault wrote.
  • DDL as files: vaultDdl() returns the tables, keys, indexes, checks, triggers and grants in the layout of a repository schema directory, and the aiq-vault-ddl command writes them, checks a directory against them and lists their order. Every file can run again, and nothing drops a table.
  • Rows only move forward: triggers keep versions and audit events append-only, and refuse a seal epoch that does not advance by one, a retired key version made current again, a data key rewrapped to an older key version, an item whose current version goes back or names a missing version, and any change to a deleted item, even from the owner.
  • Deadlock retries: a transaction SQL Server chose as a deadlock victim runs again from its start (@aiquants/mssql).

It needs Node 24 or later, SQL Server 2017 or later (STRING_AGG, OPENJSON at compatibility level 130 or more), and a node-mssql pool that keeps the default SET options (ANSI_NULLS, QUOTED_IDENTIFIER and the others a filtered index needs).

Install

pnpm add @aiquants/vault-drizzle @aiquants/vault-core drizzle-orm mssql zod
# peers: @aiquants/vault-core ^0.6.0, drizzle-orm >=1.0.0-beta.4 <2.0.0, mssql ^11.0.1 (optional: only @aiquants/vault-drizzle/node-mssql loads it)

Inside this monorepo, depend on it with workspace:*. Build and test from the package directory:

pnpm run build
pnpm run test

Database setup

The vault lives in one schema of your choice. Three principals keep its duties apart:

| Principal | Used by | Rights | | --- | --- | --- | | Owner | Applying the DDL | Owns the schema, may create tables. Never used by the server or a ceremony | | Runtime | The server | Reads every table; inserts compartments, items, versions, data keys and audit events; updates a compartment's name and stamps, an item's name, current version and stamps, and the seal epoch. No delete, no ALTER | | Ceremony | The administration CLI | Reads every table; inserts the state, key versions, items, versions, data keys and audit events; retires a key version and rewraps data keys. It adds and changes no compartment, updates no item and not the seal epoch |

Create the schema and the principals once, as an administrator:

CREATE SCHEMA [vault] AUTHORIZATION [vault_owner];
GRANT CREATE TABLE TO [vault_owner];
-- vault_runtime and vault_ceremony: users (or roles your logins belong to)

Then write the files and apply them as the owner, in their order (with sqlcmd, or your schema tooling). The aiq-vault-ddl command writes them into your schema directory, checks that the directory still holds exactly them (for a test of your repository, after an upgrade of this package) and prints the order to apply them in:

NAMES="--schema vault --database app --runtime vault_runtime --ceremony vault_ceremony"
pnpm exec aiq-vault-ddl $NAMES --out db/app/vault     # write every file (tables/ is created)
pnpm exec aiq-vault-ddl $NAMES --check db/app/vault   # exit 0 when the directory holds exactly these files, byte for byte; 1 naming each missing, differing or extra .sql file
pnpm exec aiq-vault-ddl $NAMES --list                 # the files in the order to apply them, one per line (for a sqlcmd :r list)

A usage error, a name outside its rule and two equal principals end with exit code 2. The same files come from code:

import { vaultDdl } from "@aiquants/vault-drizzle"

const files = vaultDdl({ schemaName: "vault", databaseName: "app", runtimePrincipal: "vault_runtime", ceremonyPrincipal: "vault_ceremony" })
// each file: { category, fileName (inside the schema directory, tables/ for the tables), sql }

| File | Holds | On a second run | | --- | --- | --- | | tables/<table>.table.sql | The table with its primary key, and the descriptions of the table and every column | The table is left as it is; the descriptions are updated | | UQ_*.sql, IX_*.sql | Unique keys and indexes (the current key version is a filtered unique index, so its file sets the seven SET options first) | An existing index is left as it is, and the run stops when its definition differs | | FK_*.sql, CK_*.sql | Foreign keys and checks | Dropped and added again, so they follow the package | | TR_*.sql | The append-only versions and audit events, the single state row, the forward-only columns (seal epoch, retired key versions, rewrapped data keys, an item's current version, fixed secret ID, compartment and creation stamp, deleted items), and the compartments (a fixed code and creation stamp; a compartment is never deleted) | Created or altered | | grant_vault_runtime.sql, grant_vault_ceremony.sql | The principals' rights | A first batch stops when permissions cannot restrain the principal (it is dbo, owns the schema, or is a member of db_owner). Then, in one transaction, every right on the schema and its tables is revoked, the listed ones are granted and every other one is denied explicitly (column by column where a column grant exists), so rights from a role such as db_datawriter do not slip through. Delete, ALTER and TAKE OWNERSHIP on the schema are denied (not CONTROL: denying it would also deny the SELECT it implies) | | FK_vault_TMVaultItem_compartment.sql (the last file) | The foreign key from an item's compartment to the compartment table | Dropped and added again. While an item names a compartment the table does not have, it writes nothing and stops with an explanation (see Upgrading from 0.2.0) |

The tables:

| Table | Holds | | --- | --- | | TMVaultState | The vault ID and the seal epoch (one row) | | TMVaultKeyset | Each key version's share set, verifier and share commitments; one is current | | TMVaultCompartment | Each compartment's code and name, with who added it and who last renamed it; the code never changes and a row is never deleted | | TMVaultItem | Each item's plaintext columns (secret ID, compartment, name, current version, stamps); its compartment is a row of TMVaultCompartment | | TDVaultItemVersion | Each version's encrypted body (append-only) | | TDVaultDataKey | Each version's wrapped data key; a rotation rewraps them | | TDVaultAuditEvent | The audit events (append-only) |

Instants are stored in UTC (datetimeoffset(3)). No file writes a row: the compartments are added by the vault (addCompartment), which records each one in the audit log. A row inserted into TMVaultCompartment by SQL directly is not in the audit log.

Upgrading from 0.2.0

0.3.0 adds TMVaultCompartment and a foreign key from TMVaultItem.compartment to it, and the vault (@aiquants/vault-core 0.5.0) keeps its compartments in that table instead of createVault's options. On a vault that already has items:

  1. Apply the 0.3.0 files in their order. Every file applies except the last one, FK_vault_TMVaultItem_compartment.sql, which stops with an explanation while an item names a compartment the table does not have yet; it writes nothing. Nothing drops a table.
  2. Start the server on 0.5.0 and unseal it. Until step 3, the items of a compartment that is not in the table are not listed, and creating or importing into it is refused.
  3. Add each compartment your items use with vault.addCompartment(context, { code, name }) (recorded, with its display name). vault.listCompartments() shows what the table has.
  4. Apply FK_vault_TMVaultItem_compartment.sql again; it adds the foreign key. Running it once more is harmless.

The audit checks (CK_vault_TDVaultAuditEvent_operation) list the new operations compartment-add and compartment-rename, and they are applied in step 1, before the server writes such an event.

Quick start

import { assertLockPrincipalMember } from "@aiquants/mssql/drizzle"
import { createVault } from "@aiquants/vault-core"
import { createDrizzleVaultStorage, defineVaultSchema } from "@aiquants/vault-drizzle"
import { mssqlSessionConnection } from "@aiquants/vault-drizzle/node-mssql"
import { drizzle } from "drizzle-orm/node-mssql"
import mssql from "mssql"

const pool = await new mssql.ConnectionPool(config).connect()
const db = drizzle({ client: pool })
await assertLockPrincipalMember(db, "vault_lock", "VAULT_LOCK_PRINCIPAL")   // at start-up, before serving (see below)
const storage = createDrizzleVaultStorage({
    db,
    schema: defineVaultSchema("vault"),
    lockTimeoutMs: 10_000,
    ceremonyLockTimeoutMs: 600_000,
    lockPrincipal: "vault_lock",   // the database role of the vault's own logins (see below)
    transactionRetry: { attempts: 3, onRetry: (info) => logger.warn("vault transaction retried", { attempt: info.attempt }) },
    // The ceremony lock lives on a session, so it needs a connection of its own (see below)
    openSessionConnection: () => mssqlSessionConnection(config),   // the same principal's node-mssql config, without pool
})
const vault = createVault({ storage, /* authorizer, logger, clock, secretIdRule, compartmentCodeRule, compartmentOf and the other options */ })

Every option is required:

| Option | Meaning | | --- | --- | | db | The drizzle database of your pool. The storage never sets an isolation level on it (mssql 11 would leave the level on the pooled connection) | | schema | defineVaultSchema(<schema name>); the name must be a regular identifier | | lockTimeoutMs | How long a transaction waits for the keyring lock (0 to 2147483647 ms). A timeout refuses with VaultBusyError (lock-timeout) | | ceremonyLockTimeoutMs | How long a ceremony waits for another ceremony to end | | lockPrincipal | The database role the vault's locks belong to (@DbPrincipal of sp_getapplock). Only its members, and dbo and db_owner, can take them; make its members exactly the vault's own logins (the runtime and the ceremony principals). A name of 1 to 128 characters without surrounding white space; public, in any case or width (full-width letters are folded by NFKC first), is refused | | transactionRetry | @aiquants/mssql's retry of deadlock victims (attempts, delay, onRetry) | | openSessionConnection | Opens a dedicated connection for the ceremony lock; every statement must run on the same session, so use a pool of exactly one connection that is never closed while idle (max: 1, min: 1). The storage closes it after the ceremony |

mssqlSessionConnection(config) of @aiquants/vault-drizzle/node-mssql opens such a connection: a node-mssql pool of exactly one connection that is never closed while idle (max: 1, min: 1), with drizzle's execute and the pool's close. Pass the config of the principal that runs the ceremonies, without pool: a config that sets its own pool is refused (VaultDrizzleError, storage-option) rather than overridden, since a pool of more connections, or one that closes an idle connection, would drop the lock in the middle of a ceremony.

Check the lock role once at start-up, before serving, with assertLockPrincipalMember(db, <the role>, <the name of the setting it came from>) of @aiquants/mssql/drizzle (0.4.0 or later): it confirms that the role exists and that the connection's database user can take its locks (a member, dbo or a member of db_owner), and its refusal names the setting. The storage only checks the role's name: it does not know when the host starts, and a host that skips the check stops at its first lock instead, which SQL Server refuses.

Behaviours to know

  • Errors: a duplicate secret ID refuses with VaultConflictError (secret-id-exists), a duplicate compartment code with compartment-exists, a duplicate version or data key with version-mismatch, a second state row with VaultCeremonyConflictError (already-initialized), and a second current key version, or retiring one that is not current, with keyset-changed. A lock that is not granted refuses with VaultBusyError (lock-timeout, lock-cancelled, lock-deadlock, lock-error).
    • A lockPrincipal the login is not a member of is refused by SQL Server itself, with an error that names the principal, passed on as it is; the start-up check above finds it before the first lock.
    • A compartment code that differs from an existing one only in ASCII case refuses with compartment-exists too: the insert first reads the case-folded codes under a range lock held until the transaction ends, so a concurrent insert of a case variant waits and then refuses.
  • What the storage refuses on its own: VaultDrizzleError (code config). Messages name the column, never a stored value.
    • storage-option: an option or a name outside its rule.
    • storage-value: a value it cannot write as given (a binary value of the wrong length, an empty compartment list). An instant it cannot write is refused by @aiquants/mssql's column: TypeError for a value that is not a valid Date, RangeError for a year outside 1 to 9999.
    • storage-row: a stored row it cannot read back as written (an instant that is not a valid Date, a broken deletion stamp, a live item without its current version rows, two state rows, an audit row whose columns do not form an actor).
    • storage-answer: the database answered in an unexpected shape, such as a lock result that is not an integer, or an item insert that read back anything but one positive safe integer ID. A read-back row of another shape (not an object, or without id) is @aiquants/mssql's TypeError, passed on as it is.
  • No write uses an OUTPUT without INTO: the item insert reads its ID back through a table variable with outputInto of @aiquants/mssql/drizzle (OUTPUT ... INTO @out and a select of it in one batch), because SQL Server refuses an OUTPUT without INTO when the table has an enabled trigger for that action (error 334). A host may put a trigger for any action on any of the vault's tables.
  • Audit rows from a newer vault: an operation or outcome this version does not know is refused with storage-row rather than shown wrongly; upgrade the package before reading such rows, and apply the DDL of the new version (its checks list the new values).
  • Compartment filters travel as one JSON parameter read with OPENJSON, so their number never reaches the parameter limit.
  • Compartments are listed in code order under the binary collation the vault checks; renaming a compartment reads its row for update first, so two renames of one compartment run one after the other. An item of a compartment the table does not have is refused by the foreign key (SQL Server error 547, passed on as it is), though the vault checks the compartment before it gets that far.
  • Retries run the work again: on a deadlock the whole transaction, your work included, runs again from its start. The vault's work only reads and writes through the transaction it is given, so running it again is safe.
  • Triggers do not stop the owner: an owner can disable them. Run the server and ceremonies with their own principals, never with dbo, the schema owner or a db_owner member (permissions cannot restrain those; the grant files refuse the ones the applier can see).
  • Lock scope: SQL Server tells application locks apart by the database, the principal and the name, and only the principal's members (and dbo, db_owner) can take them. Every lock statement of the storage (taking, releasing, testing the mode) names lockPrincipal, so a user of the database outside that role can neither hold the vault's locks nor stall the vault on them, and a lock of the same name taken without a principal (public) is another lock.
  • Ceremony lock scope: a ceremony checks its lock only through the storage that took it (holdCeremonyLock); run the ceremony's transactions through that same storage, as the administration CLI does.

Testing

The unit tests need no database: pnpm run test. The integration tests run against a dedicated test database with an owner and a runtime principal, whose connection values come from the environment:

| Variable | Value | | --- | --- | | VAULT_DRIZZLE_TEST_MSSQL_SERVER, VAULT_DRIZZLE_TEST_MSSQL_PORT, VAULT_DRIZZLE_TEST_MSSQL_DATABASE | The test database (its schema vault is owned by the owner principal) | | VAULT_DRIZZLE_TEST_MSSQL_EXPECT_SERVERNAME | The @@SERVERNAME the test server must answer | | VAULT_DRIZZLE_TEST_MSSQL_OWNER_USER, VAULT_DRIZZLE_TEST_MSSQL_OWNER_PASSWORD | The owner principal | | VAULT_DRIZZLE_TEST_MSSQL_RUNTIME_USER, VAULT_DRIZZLE_TEST_MSSQL_RUNTIME_PASSWORD | The runtime principal | | VAULT_DRIZZLE_TEST_MSSQL_LOCK_PRINCIPAL | The test database's role the vault's locks belong to, with the owner and the runtime principals as its members |

set -a && source <an env file outside git> && set +a
pnpm run test:integration

The run stops before collecting a test when a variable is missing, and refuses a database whose name does not end with _test. Each pool, right after it connects and before any statement that touches a table, checks that @@SERVERNAME and DB_NAME() are the named server and database, and stops otherwise. It applies the DDL twice, empties the vault tables before each scenario (disabling triggers only inside that one owner transaction), and writes nothing outside the vault schema.

The client stand-in (./testing)

@aiquants/vault-drizzle/testing exports the stand-in the unit tests run drizzle over, for a host's own tests of code that runs statements through drizzle on the vault database. No production entry imports it.

  • createStandIn(answer) gives { db, statements, events, client }: a drizzle database over a stand-in node-mssql client. Every statement is recorded with its parameters and whether it ran inside a transaction (statements), and answered by answer(statement): rows and affected counts ({ recordset, rowsAffected }; drizzle reads a select's rows as arrays, in the order of the selected fields), or an Error to throw. A transaction's begin, commit and rollback are recorded in events, and, like the driver, a second request while one is in flight on a transaction's connection is refused with the code EREQINPROG.
  • sqlServerError(number, message) builds the error node-mssql throws for a SQL Server error (number, code: "EREQUEST").

It runs drizzle's node-mssql driver, so the test needs drizzle-orm and mssql installed.

License

MIT