@decryption/vault 0.3.0 → 0.4.1
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/README.md +21 -0
- package/esm/vault.js +199 -32
- package/package.json +3 -3
- package/types.d.ts +2 -2
- package/vault.d.ts +35 -2
- package/vault.js +198 -31
package/README.md
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
<a href="https://github.com/constructive-io/decryption/actions/workflows/ci.yml">
|
|
9
9
|
<img height="20" src="https://github.com/constructive-io/decryption/actions/workflows/ci.yml/badge.svg" />
|
|
10
10
|
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/decryption/blob/main/LICENSE">
|
|
12
|
+
<img height="20" alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue.svg" />
|
|
13
|
+
</a>
|
|
11
14
|
<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
15
|
</p>
|
|
13
16
|
|
|
@@ -17,6 +20,14 @@ deploys the `dcrypt-vault` pgpm module through `@pgpmjs/pglite-adapter`, and
|
|
|
17
20
|
persists the entire database as a single `@decryption/core` envelope around a
|
|
18
21
|
gzipped pgdata tarball — the file on disk leaks nothing, not even item titles.
|
|
19
22
|
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install @decryption/vault
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
20
31
|
```ts
|
|
21
32
|
import { Vault } from '@decryption/vault';
|
|
22
33
|
|
|
@@ -31,6 +42,16 @@ await vault.setField(item.id, 'password', 'password', 's3cret');
|
|
|
31
42
|
await vault.lock(); // saves, closes, zeroes key material
|
|
32
43
|
```
|
|
33
44
|
|
|
45
|
+
## Credits
|
|
46
|
+
|
|
47
|
+
**🛠 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).**
|
|
48
|
+
|
|
49
|
+
## Disclaimer
|
|
50
|
+
|
|
51
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
52
|
+
|
|
53
|
+
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.
|
|
54
|
+
|
|
34
55
|
---
|
|
35
56
|
|
|
36
57
|
## Development
|
package/esm/vault.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { decrypt,
|
|
1
|
+
import { decrypt, deriveEnvelopeKey, encryptWithDerivedKey, } from '@decryption/core';
|
|
2
2
|
import { hkdf } from '@decryption/hashes/hkdf';
|
|
3
3
|
import { sha256 } from '@decryption/hashes/sha2';
|
|
4
4
|
import { bytesToHex, randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
|
|
@@ -12,6 +12,7 @@ import { teardownPgPools } from 'pg-cache';
|
|
|
12
12
|
// contrib extensions are exports-map-only, which node10 module resolution
|
|
13
13
|
// cannot type — resolve the CJS build at runtime instead
|
|
14
14
|
const { pgcrypto } = require('@electric-sql/pglite/contrib/pgcrypto');
|
|
15
|
+
const VAULT_SCHEMA = 'dcrypt_vault';
|
|
15
16
|
const DB_KEY_INFO = 'dcrypt/db-values';
|
|
16
17
|
const DB_KEY_SALT_META = 'db_key_salt';
|
|
17
18
|
const toItem = (row) => ({
|
|
@@ -31,16 +32,14 @@ const toItem = (row) => ({
|
|
|
31
32
|
*/
|
|
32
33
|
export class Vault {
|
|
33
34
|
db;
|
|
34
|
-
|
|
35
|
+
snapshotKey;
|
|
35
36
|
dbKey;
|
|
36
37
|
file;
|
|
37
|
-
|
|
38
|
-
constructor(db, passphrase, dbKey, file, kdf) {
|
|
38
|
+
constructor(db, snapshotKey, dbKey, file) {
|
|
39
39
|
this.db = db;
|
|
40
|
-
this.
|
|
40
|
+
this.snapshotKey = snapshotKey;
|
|
41
41
|
this.dbKey = dbKey;
|
|
42
42
|
this.file = file;
|
|
43
|
-
this.kdf = kdf;
|
|
44
43
|
}
|
|
45
44
|
/** Open an existing vault file, or initialize a new one via pgpm deploy. */
|
|
46
45
|
static async open(options) {
|
|
@@ -64,38 +63,96 @@ export class Vault {
|
|
|
64
63
|
});
|
|
65
64
|
}
|
|
66
65
|
else {
|
|
67
|
-
|
|
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;
|
|
66
|
+
db = await Vault.deployFresh(modulePath);
|
|
89
67
|
await db.query('INSERT INTO dcrypt_vault.meta (key, value) VALUES ($1, $2)', [DB_KEY_SALT_META, bytesToHex(randomBytes(16))]);
|
|
90
68
|
}
|
|
69
|
+
await Vault.ensureSchema(db);
|
|
91
70
|
const salt = await Vault.readDbKeySalt(db);
|
|
92
71
|
const dbKey = deriveDbKey(passphrase, salt);
|
|
93
|
-
|
|
72
|
+
// derive the snapshot key once: every later save costs only the AEAD pass,
|
|
73
|
+
// so locking and autosave never block on Argon2id
|
|
74
|
+
const vault = new Vault(db, deriveEnvelopeKey(passphrase, kdf), dbKey, file);
|
|
94
75
|
if (!exists) {
|
|
95
76
|
await vault.save();
|
|
96
77
|
}
|
|
97
78
|
return vault;
|
|
98
79
|
}
|
|
80
|
+
/** Runs `pgpm deploy` of the dcrypt-vault module into an empty PGlite. */
|
|
81
|
+
static async deployFresh(modulePath) {
|
|
82
|
+
const handle = await registerPglite({
|
|
83
|
+
extensions: { pgcrypto },
|
|
84
|
+
extensionSql: ['CREATE EXTENSION IF NOT EXISTS pgcrypto;'],
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
const proj = new PgpmPackage(modulePath);
|
|
88
|
+
await proj.deploy(getEnvOptions({
|
|
89
|
+
pg: { database: 'postgres' },
|
|
90
|
+
deployment: { fast: true, usePlan: true, cache: false },
|
|
91
|
+
}), proj.getModuleName());
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
await teardownPgPools();
|
|
95
|
+
await handle.close();
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
// evict the cached pool so the next open never reaches this instance
|
|
99
|
+
await teardownPgPools();
|
|
100
|
+
handle.unregister();
|
|
101
|
+
await Vault.assertDeployed(handle.db);
|
|
102
|
+
// the adapter's PGlite type is resolved through the ESM declarations while
|
|
103
|
+
// this CJS build resolves the CTS ones — identical runtime class
|
|
104
|
+
return handle.db;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Adds enum values a vault file created by an older module predates. A vault
|
|
108
|
+
* is only ever deployed once — later opens restore the snapshot — so schema
|
|
109
|
+
* additions have to be applied to the loaded database as well as to
|
|
110
|
+
* `deploy/schemas/dcrypt_vault/account_types.sql`, which is what a fresh
|
|
111
|
+
* deploy and a rebuild run.
|
|
112
|
+
*/
|
|
113
|
+
static async ensureSchema(db) {
|
|
114
|
+
for (const statement of ADDED_ENUM_VALUES)
|
|
115
|
+
await db.query(statement);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* A deploy that decides it has nothing to do would leave an empty database
|
|
119
|
+
* that then silently swallows a rebuild, so prove the schema is really there.
|
|
120
|
+
*/
|
|
121
|
+
static async assertDeployed(db) {
|
|
122
|
+
const wanted = COPY_ORDER.map((spec) => spec.table);
|
|
123
|
+
const found = await db.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [VAULT_SCHEMA]);
|
|
124
|
+
const present = new Set(found.rows.map((row) => row.tablename));
|
|
125
|
+
const missing = wanted.filter((table) => !present.has(table));
|
|
126
|
+
if (missing.length > 0) {
|
|
127
|
+
throw new Error(`pgpm deployed nothing usable: ${VAULT_SCHEMA} is missing ${missing.join(', ')}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Re-deploys the pgpm module into a fresh database and copies every row
|
|
132
|
+
* across, so a vault created by an older module picks up schema changes.
|
|
133
|
+
* Values move as ciphertext and the key salt is preserved, so no plaintext
|
|
134
|
+
* is materialised and the master passphrase still opens the result.
|
|
135
|
+
*/
|
|
136
|
+
async rebuild(modulePath) {
|
|
137
|
+
const old = this.database;
|
|
138
|
+
const next = await Vault.deployFresh(modulePath);
|
|
139
|
+
const copied = {};
|
|
140
|
+
try {
|
|
141
|
+
for (const spec of COPY_ORDER) {
|
|
142
|
+
copied[spec.table] = await copyTable(old, next, spec);
|
|
143
|
+
}
|
|
144
|
+
// folders were inserted detached to satisfy their self-reference
|
|
145
|
+
await reattachFolders(old, next);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
await next.close();
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
this.db = next;
|
|
152
|
+
await old.close();
|
|
153
|
+
await this.save();
|
|
154
|
+
return { tables: COPY_ORDER.length, copied };
|
|
155
|
+
}
|
|
99
156
|
static async readDbKeySalt(db) {
|
|
100
157
|
const result = await db.query('SELECT value FROM dcrypt_vault.meta WHERE key = $1', [DB_KEY_SALT_META]);
|
|
101
158
|
if (!result.rows.length) {
|
|
@@ -114,9 +171,11 @@ export class Vault {
|
|
|
114
171
|
}
|
|
115
172
|
/** Encrypt the current database state to the vault file (atomic rename). */
|
|
116
173
|
async save() {
|
|
174
|
+
if (!this.snapshotKey)
|
|
175
|
+
throw new Error('vault is locked');
|
|
117
176
|
const dump = await this.database.dumpDataDir('gzip');
|
|
118
177
|
const tarball = new Uint8Array(await dump.arrayBuffer());
|
|
119
|
-
const envelope =
|
|
178
|
+
const envelope = encryptWithDerivedKey(tarball, this.snapshotKey);
|
|
120
179
|
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
121
180
|
await fs.mkdir(path.dirname(this.file), { recursive: true });
|
|
122
181
|
await fs.writeFile(tmp, envelope, { mode: 0o600 });
|
|
@@ -127,9 +186,19 @@ export class Vault {
|
|
|
127
186
|
if (!this.db)
|
|
128
187
|
return;
|
|
129
188
|
await this.save();
|
|
189
|
+
await this.discard();
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Close and forget the database *without* persisting it — for erasing the
|
|
193
|
+
* vault, where writing the snapshot back out would be pointless or wrong.
|
|
194
|
+
*/
|
|
195
|
+
async discard() {
|
|
196
|
+
if (!this.db)
|
|
197
|
+
return;
|
|
130
198
|
await this.db.close();
|
|
131
199
|
this.db = null;
|
|
132
|
-
this.
|
|
200
|
+
this.snapshotKey?.key.fill(0);
|
|
201
|
+
this.snapshotKey = null;
|
|
133
202
|
this.dbKey = '';
|
|
134
203
|
}
|
|
135
204
|
// ─── items ────────────────────────────────────────────────────────────────
|
|
@@ -299,10 +368,108 @@ export class Vault {
|
|
|
299
368
|
await db.exec('ROLLBACK');
|
|
300
369
|
throw error;
|
|
301
370
|
}
|
|
302
|
-
this.
|
|
371
|
+
this.snapshotKey?.key.fill(0);
|
|
372
|
+
this.snapshotKey = deriveEnvelopeKey(next, this.snapshotKey?.kdf ?? 'moderate');
|
|
303
373
|
this.dbKey = nextKey;
|
|
304
374
|
await this.save();
|
|
305
375
|
}
|
|
306
376
|
}
|
|
377
|
+
/** Mirrors `deploy/schemas/dcrypt_vault/account_types.sql`; see ensureSchema. */
|
|
378
|
+
const ADDED_ENUM_VALUES = [
|
|
379
|
+
"ALTER TYPE dcrypt_vault.item_kind ADD VALUE IF NOT EXISTS 'account'",
|
|
380
|
+
"ALTER TYPE dcrypt_vault.item_kind ADD VALUE IF NOT EXISTS 'api_key'",
|
|
381
|
+
"ALTER TYPE dcrypt_vault.field_purpose ADD VALUE IF NOT EXISTS 'token'",
|
|
382
|
+
];
|
|
383
|
+
/** Every table a vault owns, ordered so foreign keys are satisfied as we go. */
|
|
384
|
+
const COPY_ORDER = [
|
|
385
|
+
{ table: 'meta', columns: ['key', 'value'], onConflict: '(key) DO UPDATE SET value = EXCLUDED.value' },
|
|
386
|
+
{
|
|
387
|
+
table: 'folders',
|
|
388
|
+
columns: ['id', 'name', 'parent_id', 'created_at'],
|
|
389
|
+
detach: ['parent_id'],
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
table: 'items',
|
|
393
|
+
columns: [
|
|
394
|
+
'id',
|
|
395
|
+
'kind',
|
|
396
|
+
'title',
|
|
397
|
+
'folder_id',
|
|
398
|
+
'favorite',
|
|
399
|
+
'created_at',
|
|
400
|
+
'updated_at',
|
|
401
|
+
'deleted_at',
|
|
402
|
+
],
|
|
403
|
+
casts: { kind: 'dcrypt_vault.item_kind' },
|
|
404
|
+
},
|
|
405
|
+
{
|
|
406
|
+
table: 'fields',
|
|
407
|
+
columns: [
|
|
408
|
+
'id',
|
|
409
|
+
'item_id',
|
|
410
|
+
'name',
|
|
411
|
+
'purpose',
|
|
412
|
+
'value_enc',
|
|
413
|
+
'concealed',
|
|
414
|
+
'created_at',
|
|
415
|
+
'updated_at',
|
|
416
|
+
],
|
|
417
|
+
binary: ['value_enc'],
|
|
418
|
+
casts: { purpose: 'dcrypt_vault.field_purpose' },
|
|
419
|
+
},
|
|
420
|
+
{
|
|
421
|
+
table: 'password_history',
|
|
422
|
+
columns: ['id', 'field_id', 'value_enc', 'replaced_at'],
|
|
423
|
+
binary: ['value_enc'],
|
|
424
|
+
},
|
|
425
|
+
{ table: 'tags', columns: ['id', 'name'], onConflict: '(name) DO NOTHING' },
|
|
426
|
+
{ table: 'item_tags', columns: ['item_id', 'tag_id'], onConflict: 'DO NOTHING' },
|
|
427
|
+
{ table: 'urls', columns: ['id', 'item_id', 'url'], onConflict: 'DO NOTHING' },
|
|
428
|
+
{
|
|
429
|
+
table: 'audit_log',
|
|
430
|
+
columns: ['id', 'item_id', 'field_name', 'action', 'occurred_at'],
|
|
431
|
+
},
|
|
432
|
+
];
|
|
433
|
+
const copyTable = async (from, to, spec) => {
|
|
434
|
+
const binary = new Set(spec.binary ?? []);
|
|
435
|
+
const detached = new Set(spec.detach ?? []);
|
|
436
|
+
const selected = spec.columns
|
|
437
|
+
.map((column) => {
|
|
438
|
+
if (binary.has(column))
|
|
439
|
+
return `encode(${column}, 'hex') AS ${column}`;
|
|
440
|
+
if (spec.casts?.[column])
|
|
441
|
+
return `${column}::text AS ${column}`;
|
|
442
|
+
return column;
|
|
443
|
+
})
|
|
444
|
+
.join(', ');
|
|
445
|
+
const rows = await from.query(`SELECT ${selected} FROM dcrypt_vault.${spec.table}`);
|
|
446
|
+
if (!rows.rows.length)
|
|
447
|
+
return 0;
|
|
448
|
+
const placeholders = spec.columns
|
|
449
|
+
.map((column, index) => {
|
|
450
|
+
const slot = `$${index + 1}`;
|
|
451
|
+
if (binary.has(column))
|
|
452
|
+
return `decode(${slot}, 'hex')`;
|
|
453
|
+
const cast = spec.casts?.[column];
|
|
454
|
+
return cast ? `${slot}::${cast}` : slot;
|
|
455
|
+
})
|
|
456
|
+
.join(', ');
|
|
457
|
+
const conflict = spec.onConflict ? ` ON CONFLICT ${spec.onConflict}` : '';
|
|
458
|
+
const sql = `INSERT INTO dcrypt_vault.${spec.table} (${spec.columns.join(', ')}) VALUES (${placeholders})${conflict}`;
|
|
459
|
+
for (const row of rows.rows) {
|
|
460
|
+
await to.query(sql, spec.columns.map((column) => (detached.has(column) ? null : (row[column] ?? null))));
|
|
461
|
+
}
|
|
462
|
+
return rows.rows.length;
|
|
463
|
+
};
|
|
464
|
+
/** Second pass for folders, whose parent may be inserted after the child. */
|
|
465
|
+
const reattachFolders = async (from, to) => {
|
|
466
|
+
const rows = await from.query('SELECT id, parent_id FROM dcrypt_vault.folders WHERE parent_id IS NOT NULL');
|
|
467
|
+
for (const row of rows.rows) {
|
|
468
|
+
await to.query('UPDATE dcrypt_vault.folders SET parent_id = $2 WHERE id = $1', [
|
|
469
|
+
row.id,
|
|
470
|
+
row.parent_id,
|
|
471
|
+
]);
|
|
472
|
+
}
|
|
473
|
+
};
|
|
307
474
|
/** Derive the per-value encryption key from the master passphrase. */
|
|
308
475
|
export const deriveDbKey = (passphrase, saltHex) => bytesToHex(hkdf(sha256, utf8ToBytes(passphrase), utf8ToBytes(saltHex), utf8ToBytes(DB_KEY_INFO), 32));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decryption/vault",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Passphrase-locked local vault: an in-memory PGlite database deployed from pgpm modules, persisted as one encrypted snapshot",
|
|
5
5
|
"author": "Constructive <developers@constructive.io>",
|
|
6
6
|
"main": "index.js",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"local-first"
|
|
39
39
|
],
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@decryption/core": "0.
|
|
41
|
+
"@decryption/core": "0.5.1",
|
|
42
42
|
"@decryption/hashes": "0.4.0",
|
|
43
43
|
"@electric-sql/pglite": "^0.5.4",
|
|
44
44
|
"@pgpmjs/core": "^6.34.0",
|
|
@@ -49,5 +49,5 @@
|
|
|
49
49
|
"devDependencies": {
|
|
50
50
|
"makage": "0.3.0"
|
|
51
51
|
},
|
|
52
|
-
"gitHead": "
|
|
52
|
+
"gitHead": "d29d5f2e516edf049a285b30f868360d3b996db0"
|
|
53
53
|
}
|
package/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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';
|
|
1
|
+
export type ItemKind = 'login' | 'note' | 'card' | 'identity' | 'wallet' | 'totp' | 'ssh_key' | 'account' | 'api_key' | 'passkey';
|
|
2
|
+
export type FieldPurpose = 'username' | 'password' | 'totp_seed' | 'mnemonic' | 'private_key' | 'text' | 'url' | 'token';
|
|
3
3
|
export interface VaultItem {
|
|
4
4
|
id: string;
|
|
5
5
|
kind: ItemKind;
|
package/vault.d.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { KdfParams, KdfProfile } from '@decryption/core';
|
|
2
2
|
import { AuditEntry, FieldPurpose, ItemKind, TotpOptions, VaultFieldMeta, VaultFolder, VaultItem, VaultTag } from './types';
|
|
3
|
+
/** What a rebuild moved, so the UI can show that it was not a no-op. */
|
|
4
|
+
export interface RebuildReport {
|
|
5
|
+
/** Tables in the freshly deployed schema that were copied through. */
|
|
6
|
+
tables: number;
|
|
7
|
+
/** Rows carried across, per table. */
|
|
8
|
+
copied: Record<string, number>;
|
|
9
|
+
}
|
|
3
10
|
export interface OpenVaultOptions {
|
|
4
11
|
/** Path of the encrypted vault snapshot (created if missing). */
|
|
5
12
|
file: string;
|
|
@@ -17,13 +24,34 @@ export interface OpenVaultOptions {
|
|
|
17
24
|
*/
|
|
18
25
|
export declare class Vault {
|
|
19
26
|
private db;
|
|
20
|
-
private
|
|
27
|
+
private snapshotKey;
|
|
21
28
|
private dbKey;
|
|
22
29
|
private readonly file;
|
|
23
|
-
private readonly kdf;
|
|
24
30
|
private constructor();
|
|
25
31
|
/** Open an existing vault file, or initialize a new one via pgpm deploy. */
|
|
26
32
|
static open(options: OpenVaultOptions): Promise<Vault>;
|
|
33
|
+
/** Runs `pgpm deploy` of the dcrypt-vault module into an empty PGlite. */
|
|
34
|
+
private static deployFresh;
|
|
35
|
+
/**
|
|
36
|
+
* Adds enum values a vault file created by an older module predates. A vault
|
|
37
|
+
* is only ever deployed once — later opens restore the snapshot — so schema
|
|
38
|
+
* additions have to be applied to the loaded database as well as to
|
|
39
|
+
* `deploy/schemas/dcrypt_vault/account_types.sql`, which is what a fresh
|
|
40
|
+
* deploy and a rebuild run.
|
|
41
|
+
*/
|
|
42
|
+
private static ensureSchema;
|
|
43
|
+
/**
|
|
44
|
+
* A deploy that decides it has nothing to do would leave an empty database
|
|
45
|
+
* that then silently swallows a rebuild, so prove the schema is really there.
|
|
46
|
+
*/
|
|
47
|
+
private static assertDeployed;
|
|
48
|
+
/**
|
|
49
|
+
* Re-deploys the pgpm module into a fresh database and copies every row
|
|
50
|
+
* across, so a vault created by an older module picks up schema changes.
|
|
51
|
+
* Values move as ciphertext and the key salt is preserved, so no plaintext
|
|
52
|
+
* is materialised and the master passphrase still opens the result.
|
|
53
|
+
*/
|
|
54
|
+
rebuild(modulePath: string): Promise<RebuildReport>;
|
|
27
55
|
private static readDbKeySalt;
|
|
28
56
|
private get database();
|
|
29
57
|
get isLocked(): boolean;
|
|
@@ -31,6 +59,11 @@ export declare class Vault {
|
|
|
31
59
|
save(): Promise<void>;
|
|
32
60
|
/** Persist, close the database and drop key material from memory. */
|
|
33
61
|
lock(): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Close and forget the database *without* persisting it — for erasing the
|
|
64
|
+
* vault, where writing the snapshot back out would be pointless or wrong.
|
|
65
|
+
*/
|
|
66
|
+
discard(): Promise<void>;
|
|
34
67
|
createItem(kind: ItemKind, title: string, folderId?: string): Promise<VaultItem>;
|
|
35
68
|
getItem(id: string): Promise<VaultItem | null>;
|
|
36
69
|
listItems(options?: {
|
package/vault.js
CHANGED
|
@@ -48,6 +48,7 @@ const pg_cache_1 = require("pg-cache");
|
|
|
48
48
|
// contrib extensions are exports-map-only, which node10 module resolution
|
|
49
49
|
// cannot type — resolve the CJS build at runtime instead
|
|
50
50
|
const { pgcrypto } = require('@electric-sql/pglite/contrib/pgcrypto');
|
|
51
|
+
const VAULT_SCHEMA = 'dcrypt_vault';
|
|
51
52
|
const DB_KEY_INFO = 'dcrypt/db-values';
|
|
52
53
|
const DB_KEY_SALT_META = 'db_key_salt';
|
|
53
54
|
const toItem = (row) => ({
|
|
@@ -67,16 +68,14 @@ const toItem = (row) => ({
|
|
|
67
68
|
*/
|
|
68
69
|
class Vault {
|
|
69
70
|
db;
|
|
70
|
-
|
|
71
|
+
snapshotKey;
|
|
71
72
|
dbKey;
|
|
72
73
|
file;
|
|
73
|
-
|
|
74
|
-
constructor(db, passphrase, dbKey, file, kdf) {
|
|
74
|
+
constructor(db, snapshotKey, dbKey, file) {
|
|
75
75
|
this.db = db;
|
|
76
|
-
this.
|
|
76
|
+
this.snapshotKey = snapshotKey;
|
|
77
77
|
this.dbKey = dbKey;
|
|
78
78
|
this.file = file;
|
|
79
|
-
this.kdf = kdf;
|
|
80
79
|
}
|
|
81
80
|
/** Open an existing vault file, or initialize a new one via pgpm deploy. */
|
|
82
81
|
static async open(options) {
|
|
@@ -100,38 +99,96 @@ class Vault {
|
|
|
100
99
|
});
|
|
101
100
|
}
|
|
102
101
|
else {
|
|
103
|
-
|
|
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;
|
|
102
|
+
db = await Vault.deployFresh(modulePath);
|
|
125
103
|
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
104
|
}
|
|
105
|
+
await Vault.ensureSchema(db);
|
|
127
106
|
const salt = await Vault.readDbKeySalt(db);
|
|
128
107
|
const dbKey = (0, exports.deriveDbKey)(passphrase, salt);
|
|
129
|
-
|
|
108
|
+
// derive the snapshot key once: every later save costs only the AEAD pass,
|
|
109
|
+
// so locking and autosave never block on Argon2id
|
|
110
|
+
const vault = new Vault(db, (0, core_1.deriveEnvelopeKey)(passphrase, kdf), dbKey, file);
|
|
130
111
|
if (!exists) {
|
|
131
112
|
await vault.save();
|
|
132
113
|
}
|
|
133
114
|
return vault;
|
|
134
115
|
}
|
|
116
|
+
/** Runs `pgpm deploy` of the dcrypt-vault module into an empty PGlite. */
|
|
117
|
+
static async deployFresh(modulePath) {
|
|
118
|
+
const handle = await (0, pglite_adapter_1.registerPglite)({
|
|
119
|
+
extensions: { pgcrypto },
|
|
120
|
+
extensionSql: ['CREATE EXTENSION IF NOT EXISTS pgcrypto;'],
|
|
121
|
+
});
|
|
122
|
+
try {
|
|
123
|
+
const proj = new core_2.PgpmPackage(modulePath);
|
|
124
|
+
await proj.deploy((0, env_1.getEnvOptions)({
|
|
125
|
+
pg: { database: 'postgres' },
|
|
126
|
+
deployment: { fast: true, usePlan: true, cache: false },
|
|
127
|
+
}), proj.getModuleName());
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
await (0, pg_cache_1.teardownPgPools)();
|
|
131
|
+
await handle.close();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
// evict the cached pool so the next open never reaches this instance
|
|
135
|
+
await (0, pg_cache_1.teardownPgPools)();
|
|
136
|
+
handle.unregister();
|
|
137
|
+
await Vault.assertDeployed(handle.db);
|
|
138
|
+
// the adapter's PGlite type is resolved through the ESM declarations while
|
|
139
|
+
// this CJS build resolves the CTS ones — identical runtime class
|
|
140
|
+
return handle.db;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Adds enum values a vault file created by an older module predates. A vault
|
|
144
|
+
* is only ever deployed once — later opens restore the snapshot — so schema
|
|
145
|
+
* additions have to be applied to the loaded database as well as to
|
|
146
|
+
* `deploy/schemas/dcrypt_vault/account_types.sql`, which is what a fresh
|
|
147
|
+
* deploy and a rebuild run.
|
|
148
|
+
*/
|
|
149
|
+
static async ensureSchema(db) {
|
|
150
|
+
for (const statement of ADDED_ENUM_VALUES)
|
|
151
|
+
await db.query(statement);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* A deploy that decides it has nothing to do would leave an empty database
|
|
155
|
+
* that then silently swallows a rebuild, so prove the schema is really there.
|
|
156
|
+
*/
|
|
157
|
+
static async assertDeployed(db) {
|
|
158
|
+
const wanted = COPY_ORDER.map((spec) => spec.table);
|
|
159
|
+
const found = await db.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [VAULT_SCHEMA]);
|
|
160
|
+
const present = new Set(found.rows.map((row) => row.tablename));
|
|
161
|
+
const missing = wanted.filter((table) => !present.has(table));
|
|
162
|
+
if (missing.length > 0) {
|
|
163
|
+
throw new Error(`pgpm deployed nothing usable: ${VAULT_SCHEMA} is missing ${missing.join(', ')}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Re-deploys the pgpm module into a fresh database and copies every row
|
|
168
|
+
* across, so a vault created by an older module picks up schema changes.
|
|
169
|
+
* Values move as ciphertext and the key salt is preserved, so no plaintext
|
|
170
|
+
* is materialised and the master passphrase still opens the result.
|
|
171
|
+
*/
|
|
172
|
+
async rebuild(modulePath) {
|
|
173
|
+
const old = this.database;
|
|
174
|
+
const next = await Vault.deployFresh(modulePath);
|
|
175
|
+
const copied = {};
|
|
176
|
+
try {
|
|
177
|
+
for (const spec of COPY_ORDER) {
|
|
178
|
+
copied[spec.table] = await copyTable(old, next, spec);
|
|
179
|
+
}
|
|
180
|
+
// folders were inserted detached to satisfy their self-reference
|
|
181
|
+
await reattachFolders(old, next);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
await next.close();
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
this.db = next;
|
|
188
|
+
await old.close();
|
|
189
|
+
await this.save();
|
|
190
|
+
return { tables: COPY_ORDER.length, copied };
|
|
191
|
+
}
|
|
135
192
|
static async readDbKeySalt(db) {
|
|
136
193
|
const result = await db.query('SELECT value FROM dcrypt_vault.meta WHERE key = $1', [DB_KEY_SALT_META]);
|
|
137
194
|
if (!result.rows.length) {
|
|
@@ -150,9 +207,11 @@ class Vault {
|
|
|
150
207
|
}
|
|
151
208
|
/** Encrypt the current database state to the vault file (atomic rename). */
|
|
152
209
|
async save() {
|
|
210
|
+
if (!this.snapshotKey)
|
|
211
|
+
throw new Error('vault is locked');
|
|
153
212
|
const dump = await this.database.dumpDataDir('gzip');
|
|
154
213
|
const tarball = new Uint8Array(await dump.arrayBuffer());
|
|
155
|
-
const envelope = (0, core_1.
|
|
214
|
+
const envelope = (0, core_1.encryptWithDerivedKey)(tarball, this.snapshotKey);
|
|
156
215
|
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
157
216
|
await fs_1.promises.mkdir(path.dirname(this.file), { recursive: true });
|
|
158
217
|
await fs_1.promises.writeFile(tmp, envelope, { mode: 0o600 });
|
|
@@ -163,9 +222,19 @@ class Vault {
|
|
|
163
222
|
if (!this.db)
|
|
164
223
|
return;
|
|
165
224
|
await this.save();
|
|
225
|
+
await this.discard();
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Close and forget the database *without* persisting it — for erasing the
|
|
229
|
+
* vault, where writing the snapshot back out would be pointless or wrong.
|
|
230
|
+
*/
|
|
231
|
+
async discard() {
|
|
232
|
+
if (!this.db)
|
|
233
|
+
return;
|
|
166
234
|
await this.db.close();
|
|
167
235
|
this.db = null;
|
|
168
|
-
this.
|
|
236
|
+
this.snapshotKey?.key.fill(0);
|
|
237
|
+
this.snapshotKey = null;
|
|
169
238
|
this.dbKey = '';
|
|
170
239
|
}
|
|
171
240
|
// ─── items ────────────────────────────────────────────────────────────────
|
|
@@ -335,12 +404,110 @@ class Vault {
|
|
|
335
404
|
await db.exec('ROLLBACK');
|
|
336
405
|
throw error;
|
|
337
406
|
}
|
|
338
|
-
this.
|
|
407
|
+
this.snapshotKey?.key.fill(0);
|
|
408
|
+
this.snapshotKey = (0, core_1.deriveEnvelopeKey)(next, this.snapshotKey?.kdf ?? 'moderate');
|
|
339
409
|
this.dbKey = nextKey;
|
|
340
410
|
await this.save();
|
|
341
411
|
}
|
|
342
412
|
}
|
|
343
413
|
exports.Vault = Vault;
|
|
414
|
+
/** Mirrors `deploy/schemas/dcrypt_vault/account_types.sql`; see ensureSchema. */
|
|
415
|
+
const ADDED_ENUM_VALUES = [
|
|
416
|
+
"ALTER TYPE dcrypt_vault.item_kind ADD VALUE IF NOT EXISTS 'account'",
|
|
417
|
+
"ALTER TYPE dcrypt_vault.item_kind ADD VALUE IF NOT EXISTS 'api_key'",
|
|
418
|
+
"ALTER TYPE dcrypt_vault.field_purpose ADD VALUE IF NOT EXISTS 'token'",
|
|
419
|
+
];
|
|
420
|
+
/** Every table a vault owns, ordered so foreign keys are satisfied as we go. */
|
|
421
|
+
const COPY_ORDER = [
|
|
422
|
+
{ table: 'meta', columns: ['key', 'value'], onConflict: '(key) DO UPDATE SET value = EXCLUDED.value' },
|
|
423
|
+
{
|
|
424
|
+
table: 'folders',
|
|
425
|
+
columns: ['id', 'name', 'parent_id', 'created_at'],
|
|
426
|
+
detach: ['parent_id'],
|
|
427
|
+
},
|
|
428
|
+
{
|
|
429
|
+
table: 'items',
|
|
430
|
+
columns: [
|
|
431
|
+
'id',
|
|
432
|
+
'kind',
|
|
433
|
+
'title',
|
|
434
|
+
'folder_id',
|
|
435
|
+
'favorite',
|
|
436
|
+
'created_at',
|
|
437
|
+
'updated_at',
|
|
438
|
+
'deleted_at',
|
|
439
|
+
],
|
|
440
|
+
casts: { kind: 'dcrypt_vault.item_kind' },
|
|
441
|
+
},
|
|
442
|
+
{
|
|
443
|
+
table: 'fields',
|
|
444
|
+
columns: [
|
|
445
|
+
'id',
|
|
446
|
+
'item_id',
|
|
447
|
+
'name',
|
|
448
|
+
'purpose',
|
|
449
|
+
'value_enc',
|
|
450
|
+
'concealed',
|
|
451
|
+
'created_at',
|
|
452
|
+
'updated_at',
|
|
453
|
+
],
|
|
454
|
+
binary: ['value_enc'],
|
|
455
|
+
casts: { purpose: 'dcrypt_vault.field_purpose' },
|
|
456
|
+
},
|
|
457
|
+
{
|
|
458
|
+
table: 'password_history',
|
|
459
|
+
columns: ['id', 'field_id', 'value_enc', 'replaced_at'],
|
|
460
|
+
binary: ['value_enc'],
|
|
461
|
+
},
|
|
462
|
+
{ table: 'tags', columns: ['id', 'name'], onConflict: '(name) DO NOTHING' },
|
|
463
|
+
{ table: 'item_tags', columns: ['item_id', 'tag_id'], onConflict: 'DO NOTHING' },
|
|
464
|
+
{ table: 'urls', columns: ['id', 'item_id', 'url'], onConflict: 'DO NOTHING' },
|
|
465
|
+
{
|
|
466
|
+
table: 'audit_log',
|
|
467
|
+
columns: ['id', 'item_id', 'field_name', 'action', 'occurred_at'],
|
|
468
|
+
},
|
|
469
|
+
];
|
|
470
|
+
const copyTable = async (from, to, spec) => {
|
|
471
|
+
const binary = new Set(spec.binary ?? []);
|
|
472
|
+
const detached = new Set(spec.detach ?? []);
|
|
473
|
+
const selected = spec.columns
|
|
474
|
+
.map((column) => {
|
|
475
|
+
if (binary.has(column))
|
|
476
|
+
return `encode(${column}, 'hex') AS ${column}`;
|
|
477
|
+
if (spec.casts?.[column])
|
|
478
|
+
return `${column}::text AS ${column}`;
|
|
479
|
+
return column;
|
|
480
|
+
})
|
|
481
|
+
.join(', ');
|
|
482
|
+
const rows = await from.query(`SELECT ${selected} FROM dcrypt_vault.${spec.table}`);
|
|
483
|
+
if (!rows.rows.length)
|
|
484
|
+
return 0;
|
|
485
|
+
const placeholders = spec.columns
|
|
486
|
+
.map((column, index) => {
|
|
487
|
+
const slot = `$${index + 1}`;
|
|
488
|
+
if (binary.has(column))
|
|
489
|
+
return `decode(${slot}, 'hex')`;
|
|
490
|
+
const cast = spec.casts?.[column];
|
|
491
|
+
return cast ? `${slot}::${cast}` : slot;
|
|
492
|
+
})
|
|
493
|
+
.join(', ');
|
|
494
|
+
const conflict = spec.onConflict ? ` ON CONFLICT ${spec.onConflict}` : '';
|
|
495
|
+
const sql = `INSERT INTO dcrypt_vault.${spec.table} (${spec.columns.join(', ')}) VALUES (${placeholders})${conflict}`;
|
|
496
|
+
for (const row of rows.rows) {
|
|
497
|
+
await to.query(sql, spec.columns.map((column) => (detached.has(column) ? null : (row[column] ?? null))));
|
|
498
|
+
}
|
|
499
|
+
return rows.rows.length;
|
|
500
|
+
};
|
|
501
|
+
/** Second pass for folders, whose parent may be inserted after the child. */
|
|
502
|
+
const reattachFolders = async (from, to) => {
|
|
503
|
+
const rows = await from.query('SELECT id, parent_id FROM dcrypt_vault.folders WHERE parent_id IS NOT NULL');
|
|
504
|
+
for (const row of rows.rows) {
|
|
505
|
+
await to.query('UPDATE dcrypt_vault.folders SET parent_id = $2 WHERE id = $1', [
|
|
506
|
+
row.id,
|
|
507
|
+
row.parent_id,
|
|
508
|
+
]);
|
|
509
|
+
}
|
|
510
|
+
};
|
|
344
511
|
/** Derive the per-value encryption key from the master passphrase. */
|
|
345
512
|
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
513
|
exports.deriveDbKey = deriveDbKey;
|