@decryption/vault 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # @decryption/vault
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/decryption/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/decryption/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@decryption/vault"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/decryption?filename=packages%2Fvault%2Fpackage.json"/></a>
12
+ </p>
13
+
14
+
15
+ Passphrase-locked local vault runtime. Runs PostgreSQL in-process (PGlite),
16
+ deploys the `dcrypt-vault` pgpm module through `@pgpmjs/pglite-adapter`, and
17
+ persists the entire database as a single `@decryption/core` envelope around a
18
+ gzipped pgdata tarball — the file on disk leaks nothing, not even item titles.
19
+
20
+ ```ts
21
+ import { Vault } from '@decryption/vault';
22
+
23
+ const vault = await Vault.open({
24
+ file: '~/.dcrypt/data/db/vault.dcrypt',
25
+ passphrase: 'master password',
26
+ modulePath: '/path/to/pgpm-modules/dcrypt-vault',
27
+ });
28
+
29
+ const item = await vault.createItem('login', 'GitHub');
30
+ await vault.setField(item.id, 'password', 'password', 's3cret');
31
+ await vault.lock(); // saves, closes, zeroes key material
32
+ ```
33
+
34
+ ---
35
+
36
+ ## Development
37
+
38
+ ### Setup
39
+
40
+ 1. Clone the repository:
41
+
42
+ ```bash
43
+ git clone https://github.com/constructive-io/decryption.git
44
+ ```
45
+
46
+ 2. Install dependencies:
47
+
48
+ ```bash
49
+ cd decryption
50
+ pnpm install
51
+ pnpm build
52
+ ```
53
+
54
+ 3. Test the package of interest:
55
+
56
+ ```bash
57
+ cd packages/<packagename>
58
+ pnpm test:watch
59
+ ```
60
+
61
+ ## Credits
62
+
63
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
64
+
65
+ ## Disclaimer
66
+
67
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
68
+
69
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './module-path';
2
+ export * from './types';
3
+ export * from './vault';
@@ -0,0 +1,32 @@
1
+ import { existsSync } from 'fs';
2
+ import * as path from 'path';
3
+ /**
4
+ * Locates the `dcrypt-vault` pgpm module directory, used to deploy a fresh
5
+ * vault. Resolution order:
6
+ *
7
+ * 1. `DCRYPT_VAULT_MODULE` environment variable
8
+ * 2. `module/dcrypt-vault` bundled inside this package (published builds)
9
+ * 3. `pgpm-modules/dcrypt-vault` walking up from this package (workspace)
10
+ */
11
+ export const defaultModulePath = () => {
12
+ const fromEnv = process.env.DCRYPT_VAULT_MODULE;
13
+ if (fromEnv && existsSync(path.join(fromEnv, 'pgpm.plan'))) {
14
+ return fromEnv;
15
+ }
16
+ const bundled = path.resolve(__dirname, '../module/dcrypt-vault');
17
+ if (existsSync(path.join(bundled, 'pgpm.plan'))) {
18
+ return bundled;
19
+ }
20
+ let dir = __dirname;
21
+ for (let i = 0; i < 8; i++) {
22
+ const candidate = path.join(dir, 'pgpm-modules', 'dcrypt-vault');
23
+ if (existsSync(path.join(candidate, 'pgpm.plan'))) {
24
+ return candidate;
25
+ }
26
+ const parent = path.dirname(dir);
27
+ if (parent === dir)
28
+ break;
29
+ dir = parent;
30
+ }
31
+ throw new Error('cannot locate the dcrypt-vault pgpm module; set DCRYPT_VAULT_MODULE to its directory');
32
+ };
package/esm/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/esm/vault.js ADDED
@@ -0,0 +1,308 @@
1
+ import { decrypt, encrypt } from '@decryption/core';
2
+ import { hkdf } from '@decryption/hashes/hkdf';
3
+ import { sha256 } from '@decryption/hashes/sha2';
4
+ import { bytesToHex, randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
5
+ import { PGlite } from '@electric-sql/pglite';
6
+ import { PgpmPackage } from '@pgpmjs/core';
7
+ import { getEnvOptions } from '@pgpmjs/env';
8
+ import { registerPglite } from '@pgpmjs/pglite-adapter';
9
+ import { promises as fs } from 'fs';
10
+ import * as path from 'path';
11
+ import { teardownPgPools } from 'pg-cache';
12
+ // contrib extensions are exports-map-only, which node10 module resolution
13
+ // cannot type — resolve the CJS build at runtime instead
14
+ const { pgcrypto } = require('@electric-sql/pglite/contrib/pgcrypto');
15
+ const DB_KEY_INFO = 'dcrypt/db-values';
16
+ const DB_KEY_SALT_META = 'db_key_salt';
17
+ const toItem = (row) => ({
18
+ id: row.id,
19
+ kind: row.kind,
20
+ title: row.title,
21
+ folderId: row.folder_id,
22
+ favorite: row.favorite,
23
+ createdAt: row.created_at,
24
+ updatedAt: row.updated_at,
25
+ deletedAt: row.deleted_at,
26
+ });
27
+ /**
28
+ * A passphrase-locked local vault. The database lives in memory (PGlite) and is
29
+ * persisted as a single `@decryption/core` envelope around a gzipped pgdata
30
+ * tarball, so the file on disk leaks nothing — not even item titles.
31
+ */
32
+ export class Vault {
33
+ db;
34
+ passphrase;
35
+ dbKey;
36
+ file;
37
+ kdf;
38
+ constructor(db, passphrase, dbKey, file, kdf) {
39
+ this.db = db;
40
+ this.passphrase = passphrase;
41
+ this.dbKey = dbKey;
42
+ this.file = file;
43
+ this.kdf = kdf;
44
+ }
45
+ /** Open an existing vault file, or initialize a new one via pgpm deploy. */
46
+ static async open(options) {
47
+ const { file, passphrase, modulePath, kdf = 'moderate' } = options;
48
+ let exists = true;
49
+ try {
50
+ await fs.access(file);
51
+ }
52
+ catch {
53
+ exists = false;
54
+ }
55
+ let db;
56
+ if (exists) {
57
+ const envelope = new Uint8Array(await fs.readFile(file));
58
+ const tarball = decrypt(envelope, passphrase);
59
+ db = await PGlite.create({
60
+ loadDataDir: new Blob([tarball.slice().buffer], {
61
+ type: 'application/x-gzip',
62
+ }),
63
+ extensions: { pgcrypto },
64
+ });
65
+ }
66
+ else {
67
+ const handle = await registerPglite({
68
+ extensions: { pgcrypto },
69
+ extensionSql: ['CREATE EXTENSION IF NOT EXISTS pgcrypto;'],
70
+ });
71
+ try {
72
+ const proj = new PgpmPackage(modulePath);
73
+ await proj.deploy(getEnvOptions({
74
+ pg: { database: 'postgres' },
75
+ deployment: { fast: true, usePlan: true, cache: false },
76
+ }), proj.getModuleName());
77
+ }
78
+ catch (error) {
79
+ await teardownPgPools();
80
+ await handle.close();
81
+ throw error;
82
+ }
83
+ // evict the cached pool so the next open never reaches this instance
84
+ await teardownPgPools();
85
+ handle.unregister();
86
+ // the adapter's PGlite type is resolved through the ESM declarations while
87
+ // this CJS build resolves the CTS ones — identical runtime class
88
+ db = handle.db;
89
+ await db.query('INSERT INTO dcrypt_vault.meta (key, value) VALUES ($1, $2)', [DB_KEY_SALT_META, bytesToHex(randomBytes(16))]);
90
+ }
91
+ const salt = await Vault.readDbKeySalt(db);
92
+ const dbKey = deriveDbKey(passphrase, salt);
93
+ const vault = new Vault(db, passphrase, dbKey, file, kdf);
94
+ if (!exists) {
95
+ await vault.save();
96
+ }
97
+ return vault;
98
+ }
99
+ static async readDbKeySalt(db) {
100
+ const result = await db.query('SELECT value FROM dcrypt_vault.meta WHERE key = $1', [DB_KEY_SALT_META]);
101
+ if (!result.rows.length) {
102
+ throw new Error('vault is missing its db key salt — the file may be corrupt');
103
+ }
104
+ return result.rows[0].value;
105
+ }
106
+ get database() {
107
+ if (!this.db) {
108
+ throw new Error('vault is locked');
109
+ }
110
+ return this.db;
111
+ }
112
+ get isLocked() {
113
+ return this.db === null;
114
+ }
115
+ /** Encrypt the current database state to the vault file (atomic rename). */
116
+ async save() {
117
+ const dump = await this.database.dumpDataDir('gzip');
118
+ const tarball = new Uint8Array(await dump.arrayBuffer());
119
+ const envelope = encrypt(tarball, this.passphrase, { kdf: this.kdf });
120
+ const tmp = `${this.file}.${process.pid}.tmp`;
121
+ await fs.mkdir(path.dirname(this.file), { recursive: true });
122
+ await fs.writeFile(tmp, envelope, { mode: 0o600 });
123
+ await fs.rename(tmp, this.file);
124
+ }
125
+ /** Persist, close the database and drop key material from memory. */
126
+ async lock() {
127
+ if (!this.db)
128
+ return;
129
+ await this.save();
130
+ await this.db.close();
131
+ this.db = null;
132
+ this.passphrase = '';
133
+ this.dbKey = '';
134
+ }
135
+ // ─── items ────────────────────────────────────────────────────────────────
136
+ async createItem(kind, title, folderId) {
137
+ const result = await this.database.query('INSERT INTO dcrypt_vault.items (kind, title, folder_id) VALUES ($1, $2, $3) RETURNING *', [kind, title, folderId ?? null]);
138
+ return toItem(result.rows[0]);
139
+ }
140
+ async getItem(id) {
141
+ const result = await this.database.query('SELECT * FROM dcrypt_vault.items WHERE id = $1', [id]);
142
+ return result.rows.length ? toItem(result.rows[0]) : null;
143
+ }
144
+ async listItems(options = {}) {
145
+ const clauses = [
146
+ options.trashed ? 'deleted_at IS NOT NULL' : 'deleted_at IS NULL',
147
+ ];
148
+ const params = [];
149
+ if (options.kind) {
150
+ params.push(options.kind);
151
+ clauses.push(`kind = $${params.length}`);
152
+ }
153
+ if (options.folderId) {
154
+ params.push(options.folderId);
155
+ clauses.push(`folder_id = $${params.length}`);
156
+ }
157
+ const result = await this.database.query(`SELECT * FROM dcrypt_vault.items WHERE ${clauses.join(' AND ')} ORDER BY title`, params);
158
+ return result.rows.map(toItem);
159
+ }
160
+ async renameItem(id, title) {
161
+ await this.database.query('UPDATE dcrypt_vault.items SET title = $2 WHERE id = $1', [id, title]);
162
+ }
163
+ async setFavorite(id, favorite) {
164
+ await this.database.query('UPDATE dcrypt_vault.items SET favorite = $2 WHERE id = $1', [
165
+ id,
166
+ favorite,
167
+ ]);
168
+ }
169
+ async moveToFolder(id, folderId) {
170
+ await this.database.query('UPDATE dcrypt_vault.items SET folder_id = $2 WHERE id = $1', [
171
+ id,
172
+ folderId,
173
+ ]);
174
+ }
175
+ async trashItem(id) {
176
+ await this.database.query('UPDATE dcrypt_vault.items SET deleted_at = now() WHERE id = $1', [id]);
177
+ }
178
+ async restoreItem(id) {
179
+ await this.database.query('UPDATE dcrypt_vault.items SET deleted_at = NULL WHERE id = $1', [id]);
180
+ }
181
+ async deleteItemForever(id) {
182
+ await this.database.query('DELETE FROM dcrypt_vault.items WHERE id = $1', [id]);
183
+ }
184
+ async searchItems(query) {
185
+ const result = await this.database.query('SELECT * FROM dcrypt_vault.search_items($1)', [query]);
186
+ return result.rows.map(toItem);
187
+ }
188
+ // ─── fields ───────────────────────────────────────────────────────────────
189
+ async setField(itemId, name, purpose, value, concealed = true) {
190
+ await this.database.query('SELECT dcrypt_vault.set_field($1, $2, $3, $4, $5, $6)', [
191
+ itemId,
192
+ name,
193
+ purpose,
194
+ value,
195
+ this.dbKey,
196
+ concealed,
197
+ ]);
198
+ }
199
+ async revealField(itemId, name) {
200
+ const result = await this.database.query('SELECT dcrypt_vault.reveal_field($1, $2, $3) AS v', [itemId, name, this.dbKey]);
201
+ return result.rows[0].v;
202
+ }
203
+ async listFields(itemId) {
204
+ const result = await this.database.query('SELECT id, item_id, name, purpose, concealed, updated_at FROM dcrypt_vault.fields WHERE item_id = $1 ORDER BY name', [itemId]);
205
+ return result.rows.map((row) => ({
206
+ id: row.id,
207
+ itemId: row.item_id,
208
+ name: row.name,
209
+ purpose: row.purpose,
210
+ concealed: row.concealed,
211
+ updatedAt: row.updated_at,
212
+ }));
213
+ }
214
+ async deleteField(itemId, name) {
215
+ await this.database.query('DELETE FROM dcrypt_vault.fields WHERE item_id = $1 AND name = $2', [
216
+ itemId,
217
+ name,
218
+ ]);
219
+ }
220
+ // ─── totp ─────────────────────────────────────────────────────────────────
221
+ async totpCode(itemId, options = {}) {
222
+ const result = await this.database.query('SELECT dcrypt_vault.totp_code($1, $2, $3, $4) AS c', [itemId, this.dbKey, options.period ?? 30, options.digits ?? 6]);
223
+ return result.rows[0].c;
224
+ }
225
+ // ─── folders / tags / urls ────────────────────────────────────────────────
226
+ async createFolder(name, parentId) {
227
+ const result = await this.database.query('INSERT INTO dcrypt_vault.folders (name, parent_id) VALUES ($1, $2) RETURNING id, name, parent_id', [name, parentId ?? null]);
228
+ const row = result.rows[0];
229
+ return { id: row.id, name: row.name, parentId: row.parent_id };
230
+ }
231
+ async listFolders() {
232
+ const result = await this.database.query('SELECT id, name, parent_id FROM dcrypt_vault.folders ORDER BY name');
233
+ return result.rows.map((row) => ({ id: row.id, name: row.name, parentId: row.parent_id }));
234
+ }
235
+ async deleteFolder(id) {
236
+ await this.database.query('DELETE FROM dcrypt_vault.folders WHERE id = $1', [id]);
237
+ }
238
+ async tagItem(itemId, tagName) {
239
+ await this.database.query(`WITH tag AS (
240
+ INSERT INTO dcrypt_vault.tags (name) VALUES ($2)
241
+ ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
242
+ RETURNING id
243
+ )
244
+ INSERT INTO dcrypt_vault.item_tags (item_id, tag_id)
245
+ SELECT $1, tag.id FROM tag
246
+ ON CONFLICT DO NOTHING`, [itemId, tagName]);
247
+ }
248
+ async untagItem(itemId, tagName) {
249
+ await this.database.query(`DELETE FROM dcrypt_vault.item_tags it
250
+ USING dcrypt_vault.tags t
251
+ WHERE it.tag_id = t.id AND it.item_id = $1 AND t.name = $2`, [itemId, tagName]);
252
+ }
253
+ async listTags(itemId) {
254
+ const result = itemId
255
+ ? await this.database.query(`SELECT t.id, t.name FROM dcrypt_vault.tags t
256
+ JOIN dcrypt_vault.item_tags it ON it.tag_id = t.id
257
+ WHERE it.item_id = $1 ORDER BY t.name`, [itemId])
258
+ : await this.database.query('SELECT id, name FROM dcrypt_vault.tags ORDER BY name');
259
+ return result.rows;
260
+ }
261
+ async addUrl(itemId, url) {
262
+ await this.database.query('INSERT INTO dcrypt_vault.urls (item_id, url) VALUES ($1, $2) ON CONFLICT DO NOTHING', [itemId, url]);
263
+ }
264
+ async listUrls(itemId) {
265
+ const result = await this.database.query('SELECT url FROM dcrypt_vault.urls WHERE item_id = $1 ORDER BY url', [itemId]);
266
+ return result.rows.map((row) => row.url);
267
+ }
268
+ // ─── audit ────────────────────────────────────────────────────────────────
269
+ async auditLog(itemId) {
270
+ const result = itemId
271
+ ? await this.database.query('SELECT * FROM dcrypt_vault.audit_log WHERE item_id = $1 ORDER BY occurred_at DESC', [itemId])
272
+ : await this.database.query('SELECT * FROM dcrypt_vault.audit_log ORDER BY occurred_at DESC');
273
+ return result.rows.map((row) => ({
274
+ id: row.id,
275
+ itemId: row.item_id,
276
+ fieldName: row.field_name,
277
+ action: row.action,
278
+ occurredAt: row.occurred_at,
279
+ }));
280
+ }
281
+ /** Change the master passphrase; re-derives the value key and re-encrypts every field. */
282
+ async changePassphrase(next) {
283
+ const db = this.database;
284
+ const salt = bytesToHex(randomBytes(16));
285
+ const nextKey = deriveDbKey(next, salt);
286
+ await db.exec('BEGIN');
287
+ try {
288
+ await db.query(`UPDATE dcrypt_vault.fields
289
+ SET value_enc = pgp_sym_encrypt(pgp_sym_decrypt(value_enc, $1), $2, 'compress-algo=1, cipher-algo=aes256')`, [this.dbKey, nextKey]);
290
+ await db.query(`UPDATE dcrypt_vault.password_history
291
+ SET value_enc = pgp_sym_encrypt(pgp_sym_decrypt(value_enc, $1), $2, 'compress-algo=1, cipher-algo=aes256')`, [this.dbKey, nextKey]);
292
+ await db.query('UPDATE dcrypt_vault.meta SET value = $2 WHERE key = $1', [
293
+ DB_KEY_SALT_META,
294
+ salt,
295
+ ]);
296
+ await db.exec('COMMIT');
297
+ }
298
+ catch (error) {
299
+ await db.exec('ROLLBACK');
300
+ throw error;
301
+ }
302
+ this.passphrase = next;
303
+ this.dbKey = nextKey;
304
+ await this.save();
305
+ }
306
+ }
307
+ /** Derive the per-value encryption key from the master passphrase. */
308
+ export const deriveDbKey = (passphrase, saltHex) => bytesToHex(hkdf(sha256, utf8ToBytes(passphrase), utf8ToBytes(saltHex), utf8ToBytes(DB_KEY_INFO), 32));
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './module-path';
2
+ export * from './types';
3
+ export * from './vault';
package/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./module-path"), exports);
18
+ __exportStar(require("./types"), exports);
19
+ __exportStar(require("./vault"), exports);
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Locates the `dcrypt-vault` pgpm module directory, used to deploy a fresh
3
+ * vault. Resolution order:
4
+ *
5
+ * 1. `DCRYPT_VAULT_MODULE` environment variable
6
+ * 2. `module/dcrypt-vault` bundled inside this package (published builds)
7
+ * 3. `pgpm-modules/dcrypt-vault` walking up from this package (workspace)
8
+ */
9
+ export declare const defaultModulePath: () => string;
package/module-path.js ADDED
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.defaultModulePath = void 0;
37
+ const fs_1 = require("fs");
38
+ const path = __importStar(require("path"));
39
+ /**
40
+ * Locates the `dcrypt-vault` pgpm module directory, used to deploy a fresh
41
+ * vault. Resolution order:
42
+ *
43
+ * 1. `DCRYPT_VAULT_MODULE` environment variable
44
+ * 2. `module/dcrypt-vault` bundled inside this package (published builds)
45
+ * 3. `pgpm-modules/dcrypt-vault` walking up from this package (workspace)
46
+ */
47
+ const defaultModulePath = () => {
48
+ const fromEnv = process.env.DCRYPT_VAULT_MODULE;
49
+ if (fromEnv && (0, fs_1.existsSync)(path.join(fromEnv, 'pgpm.plan'))) {
50
+ return fromEnv;
51
+ }
52
+ const bundled = path.resolve(__dirname, '../module/dcrypt-vault');
53
+ if ((0, fs_1.existsSync)(path.join(bundled, 'pgpm.plan'))) {
54
+ return bundled;
55
+ }
56
+ let dir = __dirname;
57
+ for (let i = 0; i < 8; i++) {
58
+ const candidate = path.join(dir, 'pgpm-modules', 'dcrypt-vault');
59
+ if ((0, fs_1.existsSync)(path.join(candidate, 'pgpm.plan'))) {
60
+ return candidate;
61
+ }
62
+ const parent = path.dirname(dir);
63
+ if (parent === dir)
64
+ break;
65
+ dir = parent;
66
+ }
67
+ throw new Error('cannot locate the dcrypt-vault pgpm module; set DCRYPT_VAULT_MODULE to its directory');
68
+ };
69
+ exports.defaultModulePath = defaultModulePath;
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@decryption/vault",
3
+ "version": "0.3.0",
4
+ "description": "Passphrase-locked local vault: an in-memory PGlite database deployed from pgpm modules, persisted as one encrypted snapshot",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/decryption",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/decryption"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/decryption/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "makage assets",
24
+ "clean": "makage clean",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "makage build",
27
+ "lint": "eslint . --fix",
28
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
29
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
30
+ },
31
+ "keywords": [
32
+ "vault",
33
+ "pglite",
34
+ "pgpm",
35
+ "postgres",
36
+ "secrets",
37
+ "totp",
38
+ "local-first"
39
+ ],
40
+ "dependencies": {
41
+ "@decryption/core": "0.4.0",
42
+ "@decryption/hashes": "0.4.0",
43
+ "@electric-sql/pglite": "^0.5.4",
44
+ "@pgpmjs/core": "^6.34.0",
45
+ "@pgpmjs/env": "^2.30.2",
46
+ "@pgpmjs/pglite-adapter": "^0.1.5",
47
+ "pg-cache": "^3.16.2"
48
+ },
49
+ "devDependencies": {
50
+ "makage": "0.3.0"
51
+ },
52
+ "gitHead": "49eff05f5fa934d2d045372f0ddb4626190822dd"
53
+ }
package/types.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ export type ItemKind = 'login' | 'note' | 'card' | 'identity' | 'wallet' | 'totp' | 'ssh_key';
2
+ export type FieldPurpose = 'username' | 'password' | 'totp_seed' | 'mnemonic' | 'private_key' | 'text' | 'url';
3
+ export interface VaultItem {
4
+ id: string;
5
+ kind: ItemKind;
6
+ title: string;
7
+ folderId: string | null;
8
+ favorite: boolean;
9
+ createdAt: string;
10
+ updatedAt: string;
11
+ deletedAt: string | null;
12
+ }
13
+ export interface VaultFieldMeta {
14
+ id: string;
15
+ itemId: string;
16
+ name: string;
17
+ purpose: FieldPurpose;
18
+ concealed: boolean;
19
+ updatedAt: string;
20
+ }
21
+ export interface VaultFolder {
22
+ id: string;
23
+ name: string;
24
+ parentId: string | null;
25
+ }
26
+ export interface VaultTag {
27
+ id: string;
28
+ name: string;
29
+ }
30
+ export interface AuditEntry {
31
+ id: string;
32
+ itemId: string | null;
33
+ fieldName: string | null;
34
+ action: string;
35
+ occurredAt: string;
36
+ }
37
+ export interface TotpOptions {
38
+ period?: number;
39
+ digits?: number;
40
+ }
package/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/vault.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { KdfParams, KdfProfile } from '@decryption/core';
2
+ import { AuditEntry, FieldPurpose, ItemKind, TotpOptions, VaultFieldMeta, VaultFolder, VaultItem, VaultTag } from './types';
3
+ export interface OpenVaultOptions {
4
+ /** Path of the encrypted vault snapshot (created if missing). */
5
+ file: string;
6
+ /** Master passphrase; never persisted. */
7
+ passphrase: string;
8
+ /** Directory of the dcrypt-vault pgpm module, used to deploy a fresh vault. */
9
+ modulePath: string;
10
+ /** KDF cost for the snapshot envelope. */
11
+ kdf?: KdfProfile | KdfParams;
12
+ }
13
+ /**
14
+ * A passphrase-locked local vault. The database lives in memory (PGlite) and is
15
+ * persisted as a single `@decryption/core` envelope around a gzipped pgdata
16
+ * tarball, so the file on disk leaks nothing — not even item titles.
17
+ */
18
+ export declare class Vault {
19
+ private db;
20
+ private passphrase;
21
+ private dbKey;
22
+ private readonly file;
23
+ private readonly kdf;
24
+ private constructor();
25
+ /** Open an existing vault file, or initialize a new one via pgpm deploy. */
26
+ static open(options: OpenVaultOptions): Promise<Vault>;
27
+ private static readDbKeySalt;
28
+ private get database();
29
+ get isLocked(): boolean;
30
+ /** Encrypt the current database state to the vault file (atomic rename). */
31
+ save(): Promise<void>;
32
+ /** Persist, close the database and drop key material from memory. */
33
+ lock(): Promise<void>;
34
+ createItem(kind: ItemKind, title: string, folderId?: string): Promise<VaultItem>;
35
+ getItem(id: string): Promise<VaultItem | null>;
36
+ listItems(options?: {
37
+ kind?: ItemKind;
38
+ folderId?: string;
39
+ trashed?: boolean;
40
+ }): Promise<VaultItem[]>;
41
+ renameItem(id: string, title: string): Promise<void>;
42
+ setFavorite(id: string, favorite: boolean): Promise<void>;
43
+ moveToFolder(id: string, folderId: string | null): Promise<void>;
44
+ trashItem(id: string): Promise<void>;
45
+ restoreItem(id: string): Promise<void>;
46
+ deleteItemForever(id: string): Promise<void>;
47
+ searchItems(query: string): Promise<VaultItem[]>;
48
+ setField(itemId: string, name: string, purpose: FieldPurpose, value: string, concealed?: boolean): Promise<void>;
49
+ revealField(itemId: string, name: string): Promise<string>;
50
+ listFields(itemId: string): Promise<VaultFieldMeta[]>;
51
+ deleteField(itemId: string, name: string): Promise<void>;
52
+ totpCode(itemId: string, options?: TotpOptions): Promise<string>;
53
+ createFolder(name: string, parentId?: string): Promise<VaultFolder>;
54
+ listFolders(): Promise<VaultFolder[]>;
55
+ deleteFolder(id: string): Promise<void>;
56
+ tagItem(itemId: string, tagName: string): Promise<void>;
57
+ untagItem(itemId: string, tagName: string): Promise<void>;
58
+ listTags(itemId?: string): Promise<VaultTag[]>;
59
+ addUrl(itemId: string, url: string): Promise<void>;
60
+ listUrls(itemId: string): Promise<string[]>;
61
+ auditLog(itemId?: string): Promise<AuditEntry[]>;
62
+ /** Change the master passphrase; re-derives the value key and re-encrypts every field. */
63
+ changePassphrase(next: string): Promise<void>;
64
+ }
65
+ /** Derive the per-value encryption key from the master passphrase. */
66
+ export declare const deriveDbKey: (passphrase: string, saltHex: string) => string;
package/vault.js ADDED
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.deriveDbKey = exports.Vault = void 0;
37
+ const core_1 = require("@decryption/core");
38
+ const hkdf_1 = require("@decryption/hashes/hkdf");
39
+ const sha2_1 = require("@decryption/hashes/sha2");
40
+ const utils_1 = require("@decryption/hashes/utils");
41
+ const pglite_1 = require("@electric-sql/pglite");
42
+ const core_2 = require("@pgpmjs/core");
43
+ const env_1 = require("@pgpmjs/env");
44
+ const pglite_adapter_1 = require("@pgpmjs/pglite-adapter");
45
+ const fs_1 = require("fs");
46
+ const path = __importStar(require("path"));
47
+ const pg_cache_1 = require("pg-cache");
48
+ // contrib extensions are exports-map-only, which node10 module resolution
49
+ // cannot type — resolve the CJS build at runtime instead
50
+ const { pgcrypto } = require('@electric-sql/pglite/contrib/pgcrypto');
51
+ const DB_KEY_INFO = 'dcrypt/db-values';
52
+ const DB_KEY_SALT_META = 'db_key_salt';
53
+ const toItem = (row) => ({
54
+ id: row.id,
55
+ kind: row.kind,
56
+ title: row.title,
57
+ folderId: row.folder_id,
58
+ favorite: row.favorite,
59
+ createdAt: row.created_at,
60
+ updatedAt: row.updated_at,
61
+ deletedAt: row.deleted_at,
62
+ });
63
+ /**
64
+ * A passphrase-locked local vault. The database lives in memory (PGlite) and is
65
+ * persisted as a single `@decryption/core` envelope around a gzipped pgdata
66
+ * tarball, so the file on disk leaks nothing — not even item titles.
67
+ */
68
+ class Vault {
69
+ db;
70
+ passphrase;
71
+ dbKey;
72
+ file;
73
+ kdf;
74
+ constructor(db, passphrase, dbKey, file, kdf) {
75
+ this.db = db;
76
+ this.passphrase = passphrase;
77
+ this.dbKey = dbKey;
78
+ this.file = file;
79
+ this.kdf = kdf;
80
+ }
81
+ /** Open an existing vault file, or initialize a new one via pgpm deploy. */
82
+ static async open(options) {
83
+ const { file, passphrase, modulePath, kdf = 'moderate' } = options;
84
+ let exists = true;
85
+ try {
86
+ await fs_1.promises.access(file);
87
+ }
88
+ catch {
89
+ exists = false;
90
+ }
91
+ let db;
92
+ if (exists) {
93
+ const envelope = new Uint8Array(await fs_1.promises.readFile(file));
94
+ const tarball = (0, core_1.decrypt)(envelope, passphrase);
95
+ db = await pglite_1.PGlite.create({
96
+ loadDataDir: new Blob([tarball.slice().buffer], {
97
+ type: 'application/x-gzip',
98
+ }),
99
+ extensions: { pgcrypto },
100
+ });
101
+ }
102
+ else {
103
+ const handle = await (0, pglite_adapter_1.registerPglite)({
104
+ extensions: { pgcrypto },
105
+ extensionSql: ['CREATE EXTENSION IF NOT EXISTS pgcrypto;'],
106
+ });
107
+ try {
108
+ const proj = new core_2.PgpmPackage(modulePath);
109
+ await proj.deploy((0, env_1.getEnvOptions)({
110
+ pg: { database: 'postgres' },
111
+ deployment: { fast: true, usePlan: true, cache: false },
112
+ }), proj.getModuleName());
113
+ }
114
+ catch (error) {
115
+ await (0, pg_cache_1.teardownPgPools)();
116
+ await handle.close();
117
+ throw error;
118
+ }
119
+ // evict the cached pool so the next open never reaches this instance
120
+ await (0, pg_cache_1.teardownPgPools)();
121
+ handle.unregister();
122
+ // the adapter's PGlite type is resolved through the ESM declarations while
123
+ // this CJS build resolves the CTS ones — identical runtime class
124
+ db = handle.db;
125
+ await db.query('INSERT INTO dcrypt_vault.meta (key, value) VALUES ($1, $2)', [DB_KEY_SALT_META, (0, utils_1.bytesToHex)((0, utils_1.randomBytes)(16))]);
126
+ }
127
+ const salt = await Vault.readDbKeySalt(db);
128
+ const dbKey = (0, exports.deriveDbKey)(passphrase, salt);
129
+ const vault = new Vault(db, passphrase, dbKey, file, kdf);
130
+ if (!exists) {
131
+ await vault.save();
132
+ }
133
+ return vault;
134
+ }
135
+ static async readDbKeySalt(db) {
136
+ const result = await db.query('SELECT value FROM dcrypt_vault.meta WHERE key = $1', [DB_KEY_SALT_META]);
137
+ if (!result.rows.length) {
138
+ throw new Error('vault is missing its db key salt — the file may be corrupt');
139
+ }
140
+ return result.rows[0].value;
141
+ }
142
+ get database() {
143
+ if (!this.db) {
144
+ throw new Error('vault is locked');
145
+ }
146
+ return this.db;
147
+ }
148
+ get isLocked() {
149
+ return this.db === null;
150
+ }
151
+ /** Encrypt the current database state to the vault file (atomic rename). */
152
+ async save() {
153
+ const dump = await this.database.dumpDataDir('gzip');
154
+ const tarball = new Uint8Array(await dump.arrayBuffer());
155
+ const envelope = (0, core_1.encrypt)(tarball, this.passphrase, { kdf: this.kdf });
156
+ const tmp = `${this.file}.${process.pid}.tmp`;
157
+ await fs_1.promises.mkdir(path.dirname(this.file), { recursive: true });
158
+ await fs_1.promises.writeFile(tmp, envelope, { mode: 0o600 });
159
+ await fs_1.promises.rename(tmp, this.file);
160
+ }
161
+ /** Persist, close the database and drop key material from memory. */
162
+ async lock() {
163
+ if (!this.db)
164
+ return;
165
+ await this.save();
166
+ await this.db.close();
167
+ this.db = null;
168
+ this.passphrase = '';
169
+ this.dbKey = '';
170
+ }
171
+ // ─── items ────────────────────────────────────────────────────────────────
172
+ async createItem(kind, title, folderId) {
173
+ const result = await this.database.query('INSERT INTO dcrypt_vault.items (kind, title, folder_id) VALUES ($1, $2, $3) RETURNING *', [kind, title, folderId ?? null]);
174
+ return toItem(result.rows[0]);
175
+ }
176
+ async getItem(id) {
177
+ const result = await this.database.query('SELECT * FROM dcrypt_vault.items WHERE id = $1', [id]);
178
+ return result.rows.length ? toItem(result.rows[0]) : null;
179
+ }
180
+ async listItems(options = {}) {
181
+ const clauses = [
182
+ options.trashed ? 'deleted_at IS NOT NULL' : 'deleted_at IS NULL',
183
+ ];
184
+ const params = [];
185
+ if (options.kind) {
186
+ params.push(options.kind);
187
+ clauses.push(`kind = $${params.length}`);
188
+ }
189
+ if (options.folderId) {
190
+ params.push(options.folderId);
191
+ clauses.push(`folder_id = $${params.length}`);
192
+ }
193
+ const result = await this.database.query(`SELECT * FROM dcrypt_vault.items WHERE ${clauses.join(' AND ')} ORDER BY title`, params);
194
+ return result.rows.map(toItem);
195
+ }
196
+ async renameItem(id, title) {
197
+ await this.database.query('UPDATE dcrypt_vault.items SET title = $2 WHERE id = $1', [id, title]);
198
+ }
199
+ async setFavorite(id, favorite) {
200
+ await this.database.query('UPDATE dcrypt_vault.items SET favorite = $2 WHERE id = $1', [
201
+ id,
202
+ favorite,
203
+ ]);
204
+ }
205
+ async moveToFolder(id, folderId) {
206
+ await this.database.query('UPDATE dcrypt_vault.items SET folder_id = $2 WHERE id = $1', [
207
+ id,
208
+ folderId,
209
+ ]);
210
+ }
211
+ async trashItem(id) {
212
+ await this.database.query('UPDATE dcrypt_vault.items SET deleted_at = now() WHERE id = $1', [id]);
213
+ }
214
+ async restoreItem(id) {
215
+ await this.database.query('UPDATE dcrypt_vault.items SET deleted_at = NULL WHERE id = $1', [id]);
216
+ }
217
+ async deleteItemForever(id) {
218
+ await this.database.query('DELETE FROM dcrypt_vault.items WHERE id = $1', [id]);
219
+ }
220
+ async searchItems(query) {
221
+ const result = await this.database.query('SELECT * FROM dcrypt_vault.search_items($1)', [query]);
222
+ return result.rows.map(toItem);
223
+ }
224
+ // ─── fields ───────────────────────────────────────────────────────────────
225
+ async setField(itemId, name, purpose, value, concealed = true) {
226
+ await this.database.query('SELECT dcrypt_vault.set_field($1, $2, $3, $4, $5, $6)', [
227
+ itemId,
228
+ name,
229
+ purpose,
230
+ value,
231
+ this.dbKey,
232
+ concealed,
233
+ ]);
234
+ }
235
+ async revealField(itemId, name) {
236
+ const result = await this.database.query('SELECT dcrypt_vault.reveal_field($1, $2, $3) AS v', [itemId, name, this.dbKey]);
237
+ return result.rows[0].v;
238
+ }
239
+ async listFields(itemId) {
240
+ const result = await this.database.query('SELECT id, item_id, name, purpose, concealed, updated_at FROM dcrypt_vault.fields WHERE item_id = $1 ORDER BY name', [itemId]);
241
+ return result.rows.map((row) => ({
242
+ id: row.id,
243
+ itemId: row.item_id,
244
+ name: row.name,
245
+ purpose: row.purpose,
246
+ concealed: row.concealed,
247
+ updatedAt: row.updated_at,
248
+ }));
249
+ }
250
+ async deleteField(itemId, name) {
251
+ await this.database.query('DELETE FROM dcrypt_vault.fields WHERE item_id = $1 AND name = $2', [
252
+ itemId,
253
+ name,
254
+ ]);
255
+ }
256
+ // ─── totp ─────────────────────────────────────────────────────────────────
257
+ async totpCode(itemId, options = {}) {
258
+ const result = await this.database.query('SELECT dcrypt_vault.totp_code($1, $2, $3, $4) AS c', [itemId, this.dbKey, options.period ?? 30, options.digits ?? 6]);
259
+ return result.rows[0].c;
260
+ }
261
+ // ─── folders / tags / urls ────────────────────────────────────────────────
262
+ async createFolder(name, parentId) {
263
+ const result = await this.database.query('INSERT INTO dcrypt_vault.folders (name, parent_id) VALUES ($1, $2) RETURNING id, name, parent_id', [name, parentId ?? null]);
264
+ const row = result.rows[0];
265
+ return { id: row.id, name: row.name, parentId: row.parent_id };
266
+ }
267
+ async listFolders() {
268
+ const result = await this.database.query('SELECT id, name, parent_id FROM dcrypt_vault.folders ORDER BY name');
269
+ return result.rows.map((row) => ({ id: row.id, name: row.name, parentId: row.parent_id }));
270
+ }
271
+ async deleteFolder(id) {
272
+ await this.database.query('DELETE FROM dcrypt_vault.folders WHERE id = $1', [id]);
273
+ }
274
+ async tagItem(itemId, tagName) {
275
+ await this.database.query(`WITH tag AS (
276
+ INSERT INTO dcrypt_vault.tags (name) VALUES ($2)
277
+ ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
278
+ RETURNING id
279
+ )
280
+ INSERT INTO dcrypt_vault.item_tags (item_id, tag_id)
281
+ SELECT $1, tag.id FROM tag
282
+ ON CONFLICT DO NOTHING`, [itemId, tagName]);
283
+ }
284
+ async untagItem(itemId, tagName) {
285
+ await this.database.query(`DELETE FROM dcrypt_vault.item_tags it
286
+ USING dcrypt_vault.tags t
287
+ WHERE it.tag_id = t.id AND it.item_id = $1 AND t.name = $2`, [itemId, tagName]);
288
+ }
289
+ async listTags(itemId) {
290
+ const result = itemId
291
+ ? await this.database.query(`SELECT t.id, t.name FROM dcrypt_vault.tags t
292
+ JOIN dcrypt_vault.item_tags it ON it.tag_id = t.id
293
+ WHERE it.item_id = $1 ORDER BY t.name`, [itemId])
294
+ : await this.database.query('SELECT id, name FROM dcrypt_vault.tags ORDER BY name');
295
+ return result.rows;
296
+ }
297
+ async addUrl(itemId, url) {
298
+ await this.database.query('INSERT INTO dcrypt_vault.urls (item_id, url) VALUES ($1, $2) ON CONFLICT DO NOTHING', [itemId, url]);
299
+ }
300
+ async listUrls(itemId) {
301
+ const result = await this.database.query('SELECT url FROM dcrypt_vault.urls WHERE item_id = $1 ORDER BY url', [itemId]);
302
+ return result.rows.map((row) => row.url);
303
+ }
304
+ // ─── audit ────────────────────────────────────────────────────────────────
305
+ async auditLog(itemId) {
306
+ const result = itemId
307
+ ? await this.database.query('SELECT * FROM dcrypt_vault.audit_log WHERE item_id = $1 ORDER BY occurred_at DESC', [itemId])
308
+ : await this.database.query('SELECT * FROM dcrypt_vault.audit_log ORDER BY occurred_at DESC');
309
+ return result.rows.map((row) => ({
310
+ id: row.id,
311
+ itemId: row.item_id,
312
+ fieldName: row.field_name,
313
+ action: row.action,
314
+ occurredAt: row.occurred_at,
315
+ }));
316
+ }
317
+ /** Change the master passphrase; re-derives the value key and re-encrypts every field. */
318
+ async changePassphrase(next) {
319
+ const db = this.database;
320
+ const salt = (0, utils_1.bytesToHex)((0, utils_1.randomBytes)(16));
321
+ const nextKey = (0, exports.deriveDbKey)(next, salt);
322
+ await db.exec('BEGIN');
323
+ try {
324
+ await db.query(`UPDATE dcrypt_vault.fields
325
+ SET value_enc = pgp_sym_encrypt(pgp_sym_decrypt(value_enc, $1), $2, 'compress-algo=1, cipher-algo=aes256')`, [this.dbKey, nextKey]);
326
+ await db.query(`UPDATE dcrypt_vault.password_history
327
+ SET value_enc = pgp_sym_encrypt(pgp_sym_decrypt(value_enc, $1), $2, 'compress-algo=1, cipher-algo=aes256')`, [this.dbKey, nextKey]);
328
+ await db.query('UPDATE dcrypt_vault.meta SET value = $2 WHERE key = $1', [
329
+ DB_KEY_SALT_META,
330
+ salt,
331
+ ]);
332
+ await db.exec('COMMIT');
333
+ }
334
+ catch (error) {
335
+ await db.exec('ROLLBACK');
336
+ throw error;
337
+ }
338
+ this.passphrase = next;
339
+ this.dbKey = nextKey;
340
+ await this.save();
341
+ }
342
+ }
343
+ exports.Vault = Vault;
344
+ /** Derive the per-value encryption key from the master passphrase. */
345
+ const deriveDbKey = (passphrase, saltHex) => (0, utils_1.bytesToHex)((0, hkdf_1.hkdf)(sha2_1.sha256, (0, utils_1.utf8ToBytes)(passphrase), (0, utils_1.utf8ToBytes)(saltHex), (0, utils_1.utf8ToBytes)(DB_KEY_INFO), 32));
346
+ exports.deriveDbKey = deriveDbKey;