@happyvertical/sql 0.111.7 → 0.111.8

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 CHANGED
@@ -292,7 +292,31 @@ replace an unencrypted user-owned database and its directory. Separating
292
292
  same-account processes requires OS sandboxing plus a descriptor-relative/custom
293
293
  SQLite VFS. Keep the custody contract in force for the full connection lifetime.
294
294
 
295
- The secure path is supported on macOS and Linux with Node.js 24.18.0 or newer.
295
+ The secure path is supported on macOS and Linux with Node.js 24.18.0 or newer,
296
+ and on Windows when the caller supplies `windowsCustody`:
297
+
298
+ ```typescript
299
+ secureFile: {
300
+ driver: 'node:sqlite',
301
+ custody: 'trusted-parent',
302
+ windowsCustody: {
303
+ // Throw or reject to refuse. Receives the drive-root-to-parent chain and,
304
+ // when it exists, the database leaf last.
305
+ verify: async (paths) => assertPrivateToCurrentUser(paths),
306
+ },
307
+ }
308
+ ```
309
+
310
+ Node cannot read NTFS ACLs, so on Windows the caller owns the trust policy
311
+ (which accounts may hold access) and the adapter owns no ACL code. The adapter
312
+ still performs its own structural walk: lexical containment under the custody
313
+ root, no symlinks or junctions (`lstat`), canonical native `realpath` equal to
314
+ each path (catches mount points and `subst` drives), a regular-file leaf with
315
+ `nlink === 1`, and a stable bigint `dev`/`ino`/`birthtimeNs` leaf identity
316
+ across checks. `verify` runs before the leaf is created and again afterwards
317
+ with the leaf appended (an existing leaf is verified on both passes); a created
318
+ leaf is removed if the second pass fails. Without `windowsCustody`, Windows
319
+ fails closed. The option is ignored on macOS and Linux.
296
320
  The runtime version is checked before `node:sqlite` is imported or the database
297
321
  is opened. Secure mode fails closed on older or malformed runtime versions,
298
322
  other platforms, and when combined with remote LibSQL URLs, `:memory:`, LibSQL
@@ -876,7 +900,7 @@ shipping it beyond development or test environments.
876
900
 
877
901
  | Adapter | `type` | Backend | Notes |
878
902
  |---------|--------|---------|-------|
879
- | SQLite | `'sqlite'` | LibSQL (`@libsql/client`) by default; built-in `node:sqlite` for capabilities and `secureFile` | Supports `:memory:`, file, and remote Turso URLs by default. Native capabilities are local-only; trusted-parent secure files are macOS/Linux-only |
903
+ | SQLite | `'sqlite'` | LibSQL (`@libsql/client`) by default; built-in `node:sqlite` for capabilities and `secureFile` | Supports `:memory:`, file, and remote Turso URLs by default. Native capabilities are local-only; trusted-parent secure files are macOS/Linux, or Windows with a caller-supplied `windowsCustody.verify` |
880
904
  | PostgreSQL | `'postgres'` | `pg` Pool | Connection pooling, pgvector support |
881
905
  | PGlite | `'pglite'` | `@electric-sql/pglite` (optional peer) | Postgres in WebAssembly. Browser-safe via `@happyvertical/sql/pglite`; persists to IndexedDB, OPFS, or a directory; single connection |
882
906
  | DuckDB | `'duckdb'` | `@duckdb/node-api` | JSON file auto-registration, write-back strategies |
@@ -9,6 +9,7 @@ import { lstat, open, unlink } from "node:fs/promises";
9
9
  import { dirname, parse, relative, resolve, sep } from "node:path";
10
10
  import { AsyncLocalStorage, createHook, executionAsyncId, executionAsyncResource } from "node:async_hooks";
11
11
  import { createHash } from "node:crypto";
12
+ import { realpath } from "node:fs";
12
13
  import { fileURLToPath } from "node:url";
13
14
  import { types } from "node:util";
14
15
  //#region src/secure-sqlite-client.ts
@@ -115,14 +116,7 @@ async function validateDarwinAcl(filePath, runtime) {
115
116
  hint: "Remove ACL entries that grant authority from the application-custodied path before requesting secure acquisition."
116
117
  });
117
118
  }
118
- async function validateTrustedParentCustody(filePath, options, runtime) {
119
- if (options.custody !== "trusted-parent") throw new DatabaseError("Secure SQLite acquisition requires trusted-parent custody", {});
120
- let currentUid;
121
- try {
122
- currentUid = (runtime.currentUid ?? defaultRuntime.currentUid)?.() ?? -1;
123
- } catch (error) {
124
- throw new DatabaseError("Secure SQLite acquisition cannot verify the current user", { originalError: error instanceof Error ? error.message : String(error) });
125
- }
119
+ function resolveCustodyLayout(filePath, options) {
126
120
  const databaseParent = dirname(filePath);
127
121
  const custodyRoot = resolve(options.root ?? databaseParent);
128
122
  const relativeDatabasePath = relative(custodyRoot, filePath);
@@ -139,6 +133,20 @@ async function validateTrustedParentCustody(filePath, options, runtime) {
139
133
  path: databaseParent,
140
134
  custodyRoot
141
135
  });
136
+ return {
137
+ databaseParent,
138
+ custodiedParents
139
+ };
140
+ }
141
+ async function validateTrustedParentCustody(filePath, options, runtime) {
142
+ if (options.custody !== "trusted-parent") throw new DatabaseError("Secure SQLite acquisition requires trusted-parent custody", {});
143
+ let currentUid;
144
+ try {
145
+ currentUid = (runtime.currentUid ?? defaultRuntime.currentUid)?.() ?? -1;
146
+ } catch (error) {
147
+ throw new DatabaseError("Secure SQLite acquisition cannot verify the current user", { originalError: error instanceof Error ? error.message : String(error) });
148
+ }
149
+ const { databaseParent, custodiedParents } = resolveCustodyLayout(filePath, options);
142
150
  for (const componentPath of pathComponents(databaseParent)) {
143
151
  let stats;
144
152
  try {
@@ -196,6 +204,84 @@ function leafIdentity(stats) {
196
204
  function sameLeafIdentity(left, right) {
197
205
  return left.dev === right.dev && left.ino === right.ino && left.birthtimeNs === right.birthtimeNs && left.ctimeNs === right.ctimeNs;
198
206
  }
207
+ function sameWindowsLeaf(left, right) {
208
+ return left.dev === right.dev && left.ino === right.ino && left.birthtimeNs === right.birthtimeNs;
209
+ }
210
+ function nativeRealpath(filePath) {
211
+ return new Promise((resolvePath, reject) => {
212
+ realpath.native(filePath, (error, resolved) => error ? reject(error) : resolvePath(resolved));
213
+ });
214
+ }
215
+ function windowsPathKey(filePath) {
216
+ return (filePath.length > parse(filePath).root.length && filePath.endsWith(sep) ? filePath.slice(0, -1) : filePath).toLowerCase();
217
+ }
218
+ async function assertWindowsCanonicalPath(filePath, runtime) {
219
+ let canonical;
220
+ try {
221
+ canonical = await (runtime.realpathPath ?? nativeRealpath)(filePath);
222
+ } catch (error) {
223
+ throw new DatabaseError("Secure SQLite custody chain contains an inaccessible component", {
224
+ path: filePath,
225
+ originalError: error instanceof Error ? error.message : String(error)
226
+ });
227
+ }
228
+ if (windowsPathKey(canonical) !== windowsPathKey(filePath)) throw new DatabaseError("Secure SQLite custody chain must not traverse reparse points, mount points, or substituted drives", {
229
+ path: filePath,
230
+ resolvedPath: canonical
231
+ });
232
+ }
233
+ /**
234
+ * win32 custody walk. Node cannot read NTFS ACLs, so the SDK owns only the
235
+ * structural checks (lexical containment, reparse points via lstat and
236
+ * realpath, regular-file leaf, nlink === 1, stable bigint identity) and
237
+ * delegates trust policy to the caller's verifier. Returns the leaf identity,
238
+ * or undefined when the leaf does not exist yet.
239
+ */
240
+ async function validateWindowsCustody(filePath, options, runtime, windowsCustody) {
241
+ if (options.custody !== "trusted-parent") throw new DatabaseError("Secure SQLite acquisition requires trusted-parent custody", {});
242
+ const { databaseParent } = resolveCustodyLayout(filePath, options);
243
+ const lstatPath = runtime.lstatPath ?? lstat;
244
+ const chain = pathComponents(databaseParent);
245
+ for (const componentPath of chain) {
246
+ let stats;
247
+ try {
248
+ stats = await lstatPath(componentPath, { bigint: true });
249
+ } catch (error) {
250
+ throw new DatabaseError("Secure SQLite custody chain contains an inaccessible component", {
251
+ path: componentPath,
252
+ originalError: error instanceof Error ? error.message : String(error)
253
+ });
254
+ }
255
+ if (stats.isSymbolicLink() || !stats.isDirectory()) throw new DatabaseError("Secure SQLite custody chain must contain only real directories", { path: componentPath });
256
+ await assertWindowsCanonicalPath(componentPath, runtime);
257
+ }
258
+ let leaf;
259
+ try {
260
+ const stats = await lstatPath(filePath, { bigint: true });
261
+ if (stats.isSymbolicLink() || !stats.isFile()) throw new DatabaseError("Secure SQLite database leaf must be a regular file", { path: filePath });
262
+ if (stats.nlink !== 1n) throw new DatabaseError("Secure SQLite database leaf must not have additional hard links", {
263
+ path: filePath,
264
+ nlink: String(stats.nlink)
265
+ });
266
+ await assertWindowsCanonicalPath(filePath, runtime);
267
+ leaf = {
268
+ birthtimeNs: stats.birthtimeNs,
269
+ dev: stats.dev,
270
+ ino: stats.ino
271
+ };
272
+ } catch (error) {
273
+ if (error.code !== "ENOENT") throw error;
274
+ }
275
+ try {
276
+ await windowsCustody.verify(Object.freeze([...chain, ...leaf ? [filePath] : []]));
277
+ } catch (error) {
278
+ throw new DatabaseError("Secure SQLite Windows custody verification failed", {
279
+ path: filePath,
280
+ originalError: error instanceof Error ? error.message : String(error)
281
+ });
282
+ }
283
+ return leaf;
284
+ }
199
285
  async function createSecureLeaf(filePath, runtime) {
200
286
  let handle;
201
287
  try {
@@ -575,9 +661,16 @@ function createClient(database) {
575
661
  */
576
662
  async function createSecureSqliteClient(url, options, runtime = defaultRuntime) {
577
663
  validateNodeVersion(runtime);
578
- if (runtime.platform !== "darwin" && runtime.platform !== "linux") throw new DatabaseError(`Secure SQLite acquisition is unsupported on ${runtime.platform}`, { hint: "secureFile requires built-in node:sqlite on macOS or Linux. Disable secureFile only if trusted-parent custody is not required." });
664
+ const windowsCustody = runtime.platform === "win32" ? options.windowsCustody : void 0;
665
+ if (runtime.platform !== "darwin" && runtime.platform !== "linux" && !windowsCustody) throw new DatabaseError(`Secure SQLite acquisition is unsupported on ${runtime.platform}`, { hint: runtime.platform === "win32" ? "On Windows, secureFile requires windowsCustody: { verify(paths) } so the caller can enforce its NTFS ACL policy. Disable secureFile only if trusted-parent custody is not required." : "secureFile requires built-in node:sqlite on macOS or Linux. Disable secureFile only if trusted-parent custody is not required." });
666
+ if (windowsCustody && typeof windowsCustody.verify !== "function") throw new DatabaseError("Secure SQLite windowsCustody requires a verify(paths) function", {});
579
667
  const filePath = resolveSecureFilePath(url);
580
- const leafExisted = await validateTrustedParentCustody(filePath, options, runtime);
668
+ let windowsLeaf;
669
+ let leafExisted;
670
+ if (windowsCustody) {
671
+ windowsLeaf = await validateWindowsCustody(filePath, options, runtime, windowsCustody);
672
+ leafExisted = windowsLeaf !== void 0;
673
+ } else leafExisted = await validateTrustedParentCustody(filePath, options, runtime);
581
674
  let nodeSqlite;
582
675
  try {
583
676
  nodeSqlite = await runtime.loadDriver();
@@ -588,10 +681,20 @@ async function createSecureSqliteClient(url, options, runtime = defaultRuntime)
588
681
  });
589
682
  }
590
683
  let createdLeaf;
684
+ if (windowsCustody && windowsLeaf) {
685
+ const recheck = await validateWindowsCustody(filePath, options, runtime, windowsCustody);
686
+ if (!recheck || !sameWindowsLeaf(windowsLeaf, recheck)) throw new DatabaseError("Secure SQLite database leaf changed during acquisition", { path: filePath });
687
+ }
591
688
  if (!leafExisted) {
592
689
  createdLeaf = await createSecureLeaf(filePath, runtime);
593
690
  try {
594
- if (!await validateTrustedParentCustody(filePath, options, runtime)) throw new DatabaseError("Secure SQLite database leaf disappeared during acquisition", { path: filePath });
691
+ let acquiredLeaf;
692
+ if (windowsCustody) {
693
+ const observed = await validateWindowsCustody(filePath, options, runtime, windowsCustody);
694
+ acquiredLeaf = observed !== void 0;
695
+ if (observed && createdLeaf && !sameWindowsLeaf(observed, createdLeaf)) throw new DatabaseError("Secure SQLite database leaf changed during acquisition", { path: filePath });
696
+ } else acquiredLeaf = await validateTrustedParentCustody(filePath, options, runtime);
697
+ if (!acquiredLeaf) throw new DatabaseError("Secure SQLite database leaf disappeared during acquisition", { path: filePath });
595
698
  if (createdLeaf) {
596
699
  let current;
597
700
  try {
@@ -1332,7 +1435,8 @@ async function getDatabase(options = {}) {
1332
1435
  if (hasNativeSqliteCapabilities(options)) throw new DatabaseError("Secure SQLite acquisition cannot be combined with native SQLite capabilities", { hint: "Use either secureFile custody or optional native capabilities for a connection, not both." });
1333
1436
  return getCachedSqliteDatabase("secure", options, () => createDatabase(options, url, () => createSecureSqliteClient(url, {
1334
1437
  custody: secureOptions.custody,
1335
- root: secureOptions.root
1438
+ root: secureOptions.root,
1439
+ windowsCustody: secureOptions.windowsCustody
1336
1440
  })));
1337
1441
  }
1338
1442
  if (hasNativeSqliteCapabilities(options)) return (await import("./sqlite-native-DngobJtv.js")).getNativeSqliteDatabase(options);
@@ -2756,4 +2860,4 @@ async function createDatabase(options, url, clientFactory = () => createLibSQLCl
2756
2860
  //#endregion
2757
2861
  export { getDatabase };
2758
2862
 
2759
- //# sourceMappingURL=sqlite-BVpWPLcf.js.map
2863
+ //# sourceMappingURL=sqlite-BdM-nAQD.js.map