@jini-ai/db 0.3.4 → 0.3.6

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.
@@ -53,6 +53,35 @@ export class PgliteOwnerLockedError extends Error {
53
53
  this.name = "PgliteOwnerLockedError";
54
54
  }
55
55
  }
56
+ const nodeOwnerFs = {
57
+ openSync,
58
+ fstatSync,
59
+ readFileSync,
60
+ closeSync,
61
+ writeFileSync,
62
+ linkSync,
63
+ rmSync,
64
+ renameSync,
65
+ mkdirSync,
66
+ rmdirSync,
67
+ statSync,
68
+ lstatSync,
69
+ chmodSync,
70
+ existsSync,
71
+ unlinkSync,
72
+ };
73
+ const nodeOwnerProcess = {
74
+ pid: process.pid,
75
+ uid: () => process.getuid?.(),
76
+ homedir,
77
+ nowMs: () => Date.now(),
78
+ kill: (pid, signal) => {
79
+ process.kill(pid, signal);
80
+ },
81
+ };
82
+ function ownerIo(ports) {
83
+ return { fs: ports.fs ?? nodeOwnerFs, proc: ports.proc ?? nodeOwnerProcess };
84
+ }
56
85
  /** The owners this process runs, by resolved data dir (a second owner in-process is refused by the lock). */
57
86
  const runningOwners = new Map();
58
87
  /**
@@ -75,11 +104,12 @@ function dirKey(dataDir) {
75
104
  */
76
105
  export function defaultPgliteSocketDir(required, optional = {}) {
77
106
  assertPlainName(required.runDirName, "runDirName");
107
+ const { proc } = ownerIo(optional);
78
108
  const key = dirKey(required.dataDir);
79
- const inHome = join(optional.home ?? homedir(), `.${required.runDirName}`, "run", key);
109
+ const inHome = join(optional.home ?? proc.homedir(), `.${required.runDirName}`, "run", key);
80
110
  if (Buffer.byteLength(join(inHome, PGLITE_SOCKET_FILE)) <= MAX_SOCKET_PATH_BYTES)
81
111
  return inHome;
82
- return join(tmpSocketParent(required.runDirName), key);
112
+ return join(tmpSocketParent(required.runDirName, proc), key);
83
113
  }
84
114
  /** A consumer-chosen file or directory name: no separator, no leading dot, so it cannot escape its parent. */
85
115
  function assertPlainName(name, what) {
@@ -87,8 +117,8 @@ function assertPlainName(name, what) {
87
117
  throw new Error(`${what} must be a plain name: '${name}'`);
88
118
  }
89
119
  /** The per-user parent of fallback socket dirs. Other users can write `/tmp`, so it is checked, never trusted. */
90
- function tmpSocketParent(runDirName) {
91
- return join("/tmp", `${runDirName}-${process.getuid?.() ?? "user"}`);
120
+ function tmpSocketParent(runDirName, proc) {
121
+ return join("/tmp", `${runDirName}-${proc.uid() ?? "user"}`);
92
122
  }
93
123
  /** Throws unless `socketPath` fits in `sun_path`. */
94
124
  export function assertSocketPathFits(socketPath) {
@@ -97,8 +127,8 @@ export function assertSocketPathFits(socketPath) {
97
127
  throw new Error(`socket path is ${bytes} bytes; Unix sockets allow at most ${MAX_SOCKET_PATH_BYTES}: ${socketPath}`);
98
128
  }
99
129
  }
100
- function ownedByOtherUser(uid) {
101
- const own = process.getuid?.();
130
+ function ownedByOtherUser(uid, proc) {
131
+ const own = proc.uid();
102
132
  return own !== undefined && uid !== own;
103
133
  }
104
134
  /**
@@ -110,30 +140,34 @@ function ownedByOtherUser(uid) {
110
140
  * on when the parent sits directly in `/tmp` (the `/tmp/<app>-<uid>` fallback).
111
141
  */
112
142
  export function ensurePrivateDir(dir, optional = {}) {
143
+ const io = ownerIo(optional);
113
144
  const parent = dirname(resolve(dir));
114
145
  if (optional.privateParent ?? dirname(parent) === "/tmp") {
115
- try {
116
- mkdirSync(parent, { mode: 0o700 });
117
- }
118
- catch (error) {
119
- if (error.code !== "EEXIST")
120
- throw error;
121
- }
122
- const stat = lstatSync(parent);
123
- if (!stat.isDirectory() || ownedByOtherUser(stat.uid) || (stat.mode & 0o077) !== 0) {
124
- throw new Error(`refusing socket parent ${parent}: not a 0700 directory owned by this user`);
125
- }
146
+ ensurePrivateParent({ parent, io });
126
147
  }
127
- mkdirSync(dir, { recursive: true, mode: 0o700 });
128
- const stat = lstatSync(dir);
129
- if (!stat.isDirectory() || stat.isSymbolicLink() || ownedByOtherUser(stat.uid)) {
148
+ io.fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
149
+ const stat = io.fs.lstatSync(dir);
150
+ if (!stat.isDirectory() || stat.isSymbolicLink() || ownedByOtherUser(stat.uid, io.proc)) {
130
151
  throw new Error(`refusing socket dir ${dir}: not a directory owned by this user`);
131
152
  }
132
- chmodSync(dir, 0o700);
153
+ io.fs.chmodSync(dir, 0o700);
154
+ }
155
+ function ensurePrivateParent({ parent, io }, _optional = {}) {
156
+ try {
157
+ io.fs.mkdirSync(parent, { mode: 0o700 });
158
+ }
159
+ catch (error) {
160
+ if (error.code !== "EEXIST")
161
+ throw error;
162
+ }
163
+ const stat = io.fs.lstatSync(parent);
164
+ if (!stat.isDirectory() || ownedByOtherUser(stat.uid, io.proc) || (stat.mode & 0o077) !== 0) {
165
+ throw new Error(`refusing socket parent ${parent}: not a 0700 directory owned by this user`);
166
+ }
133
167
  }
134
- function pidAlive(pid) {
168
+ function pidAlive(pid, proc) {
135
169
  try {
136
- process.kill(pid, 0);
170
+ proc.kill(pid, 0);
137
171
  return true;
138
172
  }
139
173
  catch (error) {
@@ -148,10 +182,10 @@ function parsePid(text) {
148
182
  /** A lock with no pid in it (left by an older build between create and write) is stale only after this long. */
149
183
  const EMPTY_LOCK_STALE_MS = 10_000;
150
184
  /** The lock file's inode, pid and age, read through one descriptor; undefined when there is none. */
151
- function inspectLock(lockPath) {
185
+ function inspectLock(lockPath, fs) {
152
186
  let fd;
153
187
  try {
154
- fd = openSync(lockPath, "r");
188
+ fd = fs.openSync(lockPath, "r");
155
189
  }
156
190
  catch (error) {
157
191
  if (error.code === "ENOENT")
@@ -159,28 +193,34 @@ function inspectLock(lockPath) {
159
193
  throw error;
160
194
  }
161
195
  try {
162
- const { ino, mtimeMs } = fstatSync(fd);
163
- return { ino, mtimeMs, pid: parsePid(readFileSync(fd, "utf8")) };
196
+ const { ino, mtimeMs } = fs.fstatSync(fd);
197
+ return { ino, mtimeMs, pid: parsePid(fs.readFileSync(fd, "utf8")) };
164
198
  }
165
199
  finally {
166
- closeSync(fd);
200
+ fs.closeSync(fd);
167
201
  }
168
202
  }
169
- /** Creates the lock with our pid already in it (write a temp file, hard-link it in): never visible empty. */
170
- function tryCreateLock(lockPath) {
171
- const temp = `${lockPath}.${process.pid}.${randomBytes(4).toString("hex")}`;
172
- writeFileSync(temp, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
203
+ /** Hard-links `existingPath` at `newPath`: false when `newPath` already exists; any other failure throws. */
204
+ function linkUnlessExists(existingPath, newPath, fs) {
173
205
  try {
174
- linkSync(temp, lockPath);
175
- return true;
206
+ fs.linkSync(existingPath, newPath);
176
207
  }
177
208
  catch (error) {
178
209
  if (error.code === "EEXIST")
179
210
  return false;
180
211
  throw error;
181
212
  }
213
+ return true;
214
+ }
215
+ /** Creates the lock with our pid already in it (write a temp file, hard-link it in): never visible empty. */
216
+ function tryCreateLock(lockPath, { fs, proc }) {
217
+ const temp = `${lockPath}.${proc.pid}.${randomBytes(4).toString("hex")}`;
218
+ fs.writeFileSync(temp, `${proc.pid}\n`, { flag: "wx", mode: 0o600 });
219
+ try {
220
+ return linkUnlessExists(temp, lockPath, fs);
221
+ }
182
222
  finally {
183
- rmSync(temp, { force: true });
223
+ fs.rmSync(temp, { force: true });
184
224
  }
185
225
  }
186
226
  /**
@@ -188,38 +228,34 @@ function tryCreateLock(lockPath) {
188
228
  * inode, so a lock another starter took over in the meantime is put back, not deleted.
189
229
  * @throws PgliteOwnerLockedError when the lock moved aside was a newer one.
190
230
  */
191
- function moveStaleLock(dataDir, lockPath, seen) {
192
- const aside = `${lockPath}.stale.${process.pid}.${randomBytes(4).toString("hex")}`;
231
+ function moveStaleLock(dataDir, lockPath, seen, { fs, proc }) {
232
+ const aside = `${lockPath}.stale.${proc.pid}.${randomBytes(4).toString("hex")}`;
193
233
  try {
194
- renameSync(lockPath, aside);
234
+ fs.renameSync(lockPath, aside);
195
235
  }
196
236
  catch (error) {
197
237
  if (error.code === "ENOENT")
198
238
  return; // another starter removed it
199
239
  throw error;
200
240
  }
201
- const moved = inspectLock(aside);
241
+ const moved = inspectLock(aside, fs);
202
242
  if (moved?.ino === seen.ino) {
203
- rmSync(aside, { force: true });
243
+ fs.rmSync(aside, { force: true });
204
244
  return;
205
245
  }
206
246
  try {
207
- linkSync(aside, lockPath);
208
- }
209
- catch (error) {
210
- if (error.code !== "EEXIST")
211
- throw error;
247
+ linkUnlessExists(aside, lockPath, fs); // a lock another starter created since stays theirs
212
248
  }
213
249
  finally {
214
- rmSync(aside, { force: true });
250
+ fs.rmSync(aside, { force: true });
215
251
  }
216
252
  throw new PgliteOwnerLockedError(dataDir, moved?.pid);
217
253
  }
218
254
  /** Whether an observed lock is eligible for takeover; a fresh empty file remains contended. */
219
- function isStaleLock(seen) {
255
+ function isStaleLock(seen, proc) {
220
256
  if (seen.pid === undefined)
221
- return Date.now() - seen.mtimeMs > EMPTY_LOCK_STALE_MS;
222
- return !pidAlive(seen.pid);
257
+ return proc.nowMs() - seen.mtimeMs > EMPTY_LOCK_STALE_MS;
258
+ return !pidAlive(seen.pid, proc);
223
259
  }
224
260
  /**
225
261
  * Serializes removal of one observed inode, then rechecks it before renaming. Without this guard,
@@ -230,10 +266,10 @@ function isStaleLock(seen) {
230
266
  * must confirm no starter is running before removing it; automatic guard takeover would recreate
231
267
  * the same compare/rename race on the guard itself.
232
268
  */
233
- function removeStaleLock(dataDir, lockPath, seen) {
269
+ function removeStaleLock(dataDir, lockPath, seen, io) {
234
270
  const guard = `${lockPath}.reaping-${seen.ino}`;
235
271
  try {
236
- mkdirSync(guard, { mode: 0o700 });
272
+ io.fs.mkdirSync(guard, { mode: 0o700 });
237
273
  }
238
274
  catch (error) {
239
275
  if (error.code === "EEXIST")
@@ -241,15 +277,15 @@ function removeStaleLock(dataDir, lockPath, seen) {
241
277
  throw error;
242
278
  }
243
279
  try {
244
- const current = inspectLock(lockPath);
280
+ const current = inspectLock(lockPath, io.fs);
245
281
  if (current?.ino !== seen.ino)
246
282
  return; // a previous reaper already removed this inode
247
- if (!isStaleLock(current))
283
+ if (!isStaleLock(current, io.proc))
248
284
  throw new PgliteOwnerLockedError(dataDir, current.pid);
249
- moveStaleLock(dataDir, lockPath, current);
285
+ moveStaleLock(dataDir, lockPath, current, io);
250
286
  }
251
287
  finally {
252
- rmdirSync(guard);
288
+ io.fs.rmdirSync(guard);
253
289
  }
254
290
  }
255
291
  /**
@@ -259,29 +295,31 @@ function removeStaleLock(dataDir, lockPath, seen) {
259
295
  * function that only removes the inode acquired by this call.
260
296
  * @complexity O(L) time/space for L bytes in a pid file; at most five acquisition attempts.
261
297
  */
262
- export function acquireOwnerLock(required) {
298
+ export function acquireOwnerLock(required, optional = {}) {
263
299
  const { dataDir } = required;
264
300
  assertPlainName(required.lockFileName, "lockFileName");
301
+ const io = ownerIo(optional);
302
+ const { fs, proc } = io;
265
303
  const lockPath = join(dataDir, required.lockFileName);
266
304
  for (let attempt = 0; attempt < 5; attempt += 1) {
267
- if (tryCreateLock(lockPath)) {
268
- const acquiredInode = statSync(lockPath).ino;
305
+ if (tryCreateLock(lockPath, io)) {
306
+ const acquiredInode = fs.statSync(lockPath).ino;
269
307
  let released = false;
270
308
  return () => {
271
309
  if (released)
272
310
  return;
273
311
  released = true;
274
- const current = inspectLock(lockPath);
275
- if (current?.ino === acquiredInode && current.pid === process.pid)
276
- rmSync(lockPath, { force: true });
312
+ const current = inspectLock(lockPath, fs);
313
+ if (current?.ino === acquiredInode && current.pid === proc.pid)
314
+ fs.rmSync(lockPath, { force: true });
277
315
  };
278
316
  }
279
- const seen = inspectLock(lockPath);
317
+ const seen = inspectLock(lockPath, fs);
280
318
  if (seen === undefined)
281
319
  continue; // released in between
282
- if (!isStaleLock(seen))
320
+ if (!isStaleLock(seen, proc))
283
321
  throw new PgliteOwnerLockedError(dataDir, seen.pid);
284
- removeStaleLock(dataDir, lockPath, seen);
322
+ removeStaleLock(dataDir, lockPath, seen, io);
285
323
  }
286
324
  throw new Error(`could not take the PGlite owner lock ${lockPath}`);
287
325
  }
@@ -295,15 +333,18 @@ export function acquireOwnerLock(required) {
295
333
  * @param required.runDirName names the default socket dir; see {@link defaultPgliteSocketDir}.
296
334
  * @param optional.socketDir default {@link defaultPgliteSocketDir}.
297
335
  * @param optional.idleInTransactionTimeoutMs default 30 s; see `PgliteSocketServer`.
336
+ * @param optional.fs / optional.proc see {@link OwnerPorts}; default Node's own.
298
337
  * @throws PgliteOwnerLockedError when another live owner holds `dataDir`.
299
338
  */
300
339
  export async function startPgliteOwner(required, optional = {}) {
340
+ const io = ownerIo(optional);
341
+ const { fs } = io;
301
342
  const dataDir = resolve(required.dataDir);
302
- const socketDir = optional.socketDir ?? defaultPgliteSocketDir({ dataDir, runDirName: required.runDirName });
343
+ const socketDir = optional.socketDir ?? defaultPgliteSocketDir({ dataDir, runDirName: required.runDirName }, io);
303
344
  const socketPath = join(socketDir, PGLITE_SOCKET_FILE);
304
345
  assertSocketPathFits(socketPath);
305
- mkdirSync(dataDir, { recursive: true, mode: 0o700 });
306
- const releaseLock = acquireOwnerLock({ dataDir, lockFileName: required.lockFileName });
346
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
347
+ const releaseLock = acquireOwnerLock({ dataDir, lockFileName: required.lockFileName }, io);
307
348
  let db;
308
349
  let server;
309
350
  // WASM initialization can await native work with no referenced Node handle. Until the socket
@@ -311,10 +352,10 @@ export async function startPgliteOwner(required, optional = {}) {
311
352
  // Release on both success and failure, so an idle or refused boot retains no extra timer.
312
353
  const startupRef = setInterval(() => { }, 1_000);
313
354
  try {
314
- ensurePrivateDir(socketDir);
355
+ ensurePrivateDir(socketDir, io);
315
356
  // We hold the lock, so a socket file here was left by a dead owner.
316
- if (existsSync(socketPath))
317
- unlinkSync(socketPath);
357
+ if (fs.existsSync(socketPath))
358
+ fs.unlinkSync(socketPath);
318
359
  db = await required.PGlite.create({ dataDir, startParams: pgliteLowMemoryStartParams(required.PGlite) });
319
360
  server = new PgliteSocketServer({
320
361
  db,
@@ -324,14 +365,14 @@ export async function startPgliteOwner(required, optional = {}) {
324
365
  log: optional.log,
325
366
  });
326
367
  await server.start();
327
- chmodSync(socketPath, 0o600);
328
- if ((statSync(socketPath).mode & 0o077) !== 0)
368
+ fs.chmodSync(socketPath, 0o600);
369
+ if ((fs.statSync(socketPath).mode & 0o077) !== 0)
329
370
  throw new Error(`socket ${socketPath} is not owner-only`);
330
371
  }
331
372
  catch (error) {
332
373
  await server?.stop().catch(() => { });
333
374
  await db?.close().catch(() => { });
334
- rmSync(socketPath, { force: true });
375
+ fs.rmSync(socketPath, { force: true });
335
376
  releaseLock();
336
377
  throw error;
337
378
  }
@@ -353,7 +394,7 @@ export async function startPgliteOwner(required, optional = {}) {
353
394
  await open.close();
354
395
  }
355
396
  finally {
356
- rmSync(socketPath, { force: true });
397
+ fs.rmSync(socketPath, { force: true });
357
398
  releaseLock();
358
399
  }
359
400
  })();
@@ -1,4 +1,29 @@
1
1
  import type { PGlite } from "@electric-sql/pglite";
2
+ /** Per-connection pending input ceiling, including the typed-message tag byte. */
3
+ export declare const MAX_CLIENT_FRAME_BYTES: number;
4
+ /** The parts of a client socket (`net.Socket`) the server uses. */
5
+ export interface SocketServerClient {
6
+ readonly writable: boolean;
7
+ setNoDelay(noDelay: boolean): unknown;
8
+ on(event: "data", listener: (data: Buffer) => void): unknown;
9
+ on(event: "error", listener: (error: Error) => void): unknown;
10
+ on(event: "close", listener: () => void): unknown;
11
+ pause(): unknown;
12
+ resume(): unknown;
13
+ write(data: Uint8Array | string): unknown;
14
+ end(): unknown;
15
+ destroy(): unknown;
16
+ }
17
+ /** The parts of a listening server (`net.Server`) the server uses. */
18
+ export interface SocketServerListener {
19
+ listen(path: string, onListening: () => void): unknown;
20
+ once(event: "error", listener: (error: Error) => void): unknown;
21
+ off(event: "error", listener: (error: Error) => void): unknown;
22
+ on(event: "error", listener: (error: Error) => void): unknown;
23
+ close(onClosed: () => void): unknown;
24
+ }
25
+ /** Creates the listener that hands each accepted client to `accept`. */
26
+ export type SocketServerFactory = (accept: (socket: SocketServerClient) => void) => SocketServerListener;
2
27
  export interface PgliteSocketServerOptions {
3
28
  /** The PGlite this server owns. Nothing else may query it while the server runs. */
4
29
  db: PGlite;
@@ -9,6 +34,8 @@ export interface PgliteSocketServerOptions {
9
34
  /** A client idle inside an open transaction this long is disconnected and rolled back. Default 30 s; 0 = never. */
10
35
  idleInTransactionTimeoutMs?: number | undefined;
11
36
  log?: ((message: string) => void) | undefined;
37
+ /** Default `node:net`'s `createServer`; a test passes a fake to script a client socket's events. */
38
+ createServer?: SocketServerFactory | undefined;
12
39
  }
13
40
  /** A Postgres ErrorResponse frame. */
14
41
  export declare function errorResponseFrame(severity: "ERROR" | "FATAL", code: string, message: string): Buffer;
@@ -4,7 +4,7 @@
4
4
  * `LICENSE.pglite-socket` at the package root). Modified 2026-09-28: see `NOTICE.md` at the
5
5
  * package root for every change from upstream.
6
6
  */
7
- import { createServer } from "node:net";
7
+ import { createServer as createNetServer } from "node:net";
8
8
  /**
9
9
  * @file One PGlite served to several processes over a Unix socket, speaking the Postgres wire
10
10
  * protocol.
@@ -34,11 +34,19 @@ const SSL_REQUEST_CODE = 80877103;
34
34
  const GSSENC_REQUEST_CODE = 80877104;
35
35
  const CANCEL_REQUEST_CODE = 80877102;
36
36
  const PROTOCOL_3 = 196608;
37
+ /** Per-connection pending input ceiling, including the typed-message tag byte. */
38
+ export const MAX_CLIENT_FRAME_BYTES = 16 * 1024 * 1024;
37
39
  /** Typed messages after which PGlite's ReadyForQuery is legitimate: Sync, Query, FunctionCall, CopyDone, CopyFail. */
38
40
  const ENDS_EXCHANGE = new Set(["S", "Q", "F", "c", "f"].map((c) => c.charCodeAt(0)));
39
41
  const READY_FOR_QUERY = "Z".charCodeAt(0);
40
42
  /** The id of work that belongs to no connection ({@link PgliteSocketServer.runExclusive}). */
41
43
  const OWNER_JOB = 0;
44
+ const netServerFactory = (accept) => createNetServer((socket) => accept(socket));
45
+ /** Refuses invalid protocol lengths before buffering or slicing. O(1) time/space. */
46
+ function assertClientFrameSize({ size, minimum }, _options = {}) {
47
+ if (size < minimum || size > MAX_CLIENT_FRAME_BYTES)
48
+ throw new Error("Invalid client frame length");
49
+ }
42
50
  /** A Postgres ErrorResponse frame. */
43
51
  export function errorResponseFrame(severity, code, message) {
44
52
  const field = (tag, value) => Buffer.concat([Buffer.from(tag), Buffer.from(`${value}\0`)]);
@@ -205,7 +213,11 @@ class Connection {
205
213
  this.onClosed = onClosed;
206
214
  socket.setNoDelay(true);
207
215
  socket.on("data", (data) => {
208
- this.chain = this.chain.then(() => this.handle(data)).catch((error) => this.close(error));
216
+ socket.pause();
217
+ this.chain = this.chain.then(() => this.handle(data)).catch((error) => this.close(error)).then(() => {
218
+ if (!this.closed)
219
+ socket.resume();
220
+ });
209
221
  });
210
222
  socket.on("error", (error) => this.close(error));
211
223
  socket.on("close", () => this.close());
@@ -233,6 +245,8 @@ class Connection {
233
245
  async handle(data) {
234
246
  if (this.closed)
235
247
  return;
248
+ if (this.buffer.length + data.length > MAX_CLIENT_FRAME_BYTES)
249
+ throw new Error("Client frame exceeds the byte limit");
236
250
  this.buffer = Buffer.concat([this.buffer, data]);
237
251
  for (;;) {
238
252
  const message = this.nextMessage();
@@ -251,36 +265,43 @@ class Connection {
251
265
  */
252
266
  nextMessage() {
253
267
  if (!this.started) {
254
- if (this.buffer.length < 8)
268
+ if (this.buffer.length < 4)
255
269
  return undefined;
256
270
  const size = this.buffer.readInt32BE(0);
271
+ assertClientFrameSize({ size, minimum: 8 });
272
+ if (this.buffer.length < 8)
273
+ return undefined;
257
274
  const code = this.buffer.readInt32BE(4);
258
275
  if (this.buffer.length < size)
259
276
  return undefined;
260
277
  const bytes = this.buffer.subarray(0, size);
261
278
  this.buffer = this.buffer.subarray(size);
262
- if (code === SSL_REQUEST_CODE || code === GSSENC_REQUEST_CODE) {
263
- this.socket.write("N");
264
- return "skip";
265
- }
266
- if (code === CANCEL_REQUEST_CODE) {
267
- this.close();
268
- return undefined;
269
- }
270
- if (code !== PROTOCOL_3)
271
- throw new Error(`unsupported protocol ${code}`);
272
- this.started = true;
273
- return { bytes, startup: true };
279
+ return this.startupMessage({ bytes, code });
274
280
  }
275
281
  if (this.buffer.length < 5)
276
282
  return undefined;
277
283
  const size = 1 + this.buffer.readInt32BE(1);
284
+ assertClientFrameSize({ size, minimum: 5 });
278
285
  if (this.buffer.length < size)
279
286
  return undefined;
280
287
  const bytes = this.buffer.subarray(0, size);
281
288
  this.buffer = this.buffer.subarray(size);
282
289
  return { bytes, startup: false };
283
290
  }
291
+ startupMessage({ bytes, code }, _optional = {}) {
292
+ if (code === SSL_REQUEST_CODE || code === GSSENC_REQUEST_CODE) {
293
+ this.socket.write("N");
294
+ return "skip";
295
+ }
296
+ if (code === CANCEL_REQUEST_CODE) {
297
+ this.close();
298
+ return undefined;
299
+ }
300
+ if (code !== PROTOCOL_3)
301
+ throw new Error(`unsupported protocol ${code}`);
302
+ this.started = true;
303
+ return { bytes, startup: true };
304
+ }
284
305
  execute(message) {
285
306
  const dropReady = !message.startup && !ENDS_EXCHANGE.has(message.bytes[0]);
286
307
  const out = frameFilter(dropReady, (data) => {
@@ -315,7 +336,7 @@ export class PgliteSocketServer {
315
336
  if (this.server !== null)
316
337
  throw new Error("socket server already started");
317
338
  await this.options.db.waitReady;
318
- const server = createServer((socket) => this.accept(socket));
339
+ const server = (this.options.createServer ?? netServerFactory)((socket) => this.accept(socket));
319
340
  this.server = server;
320
341
  await new Promise((resolve, reject) => {
321
342
  server.once("error", reject);
@@ -63,6 +63,7 @@ export declare class SqlSecretsVaultRepo implements VaultRepoPort {
63
63
  * EXPLAIN 2026-10-12: SQLite fell back to a raw-column index, Postgres to the label index). */
64
64
  findDefault(input: VaultDefaultQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
65
65
  list(input: VaultQuery, _options?: VaultOptions): Promise<VaultRecord[]>;
66
+ private assertLabelAvailable;
66
67
  put(input: {
67
68
  record: VaultRecord;
68
69
  expectedRevision: number | null;
@@ -102,19 +102,22 @@ export class SqlSecretsVaultRepo {
102
102
  // Sort identifiers in JS to avoid host database collation changing the memory contract.
103
103
  return rows.map(fromRow).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
104
104
  }
105
+ async assertLabelAvailable({ record, existing, moved, scope }, _options = {}) {
106
+ // Unchanged-label rotations need no uniqueness read; DB constraints still guard writes.
107
+ if (moved || existing?.label !== record.label) {
108
+ const duplicate = await this.kernel.run(db => this.scoped({ db, input: scope }).select("id")
109
+ .where("id", "!=", record.id).where("label", "=", record.label).limit(1).executeTakeFirst());
110
+ if (duplicate)
111
+ throw new VaultError({ code: "conflict" });
112
+ }
113
+ }
105
114
  async put(input, _options = {}) {
106
115
  return this.write(input.record.workspaceId, async () => {
107
116
  const existing = await this.find(input.record);
108
117
  assertVaultReplacement({ ...input, existing });
109
118
  const scope = this.group(input.record);
110
- // Unchanged-label rotations need no uniqueness read; DB constraints still guard writes.
111
119
  const moved = existing !== null && existing.provider !== input.record.provider;
112
- if (moved || existing?.label !== input.record.label) {
113
- const duplicate = await this.kernel.run(db => this.scoped({ db, input: scope }).select("id")
114
- .where("id", "!=", input.record.id).where("label", "=", input.record.label).limit(1).executeTakeFirst());
115
- if (duplicate)
116
- throw new VaultError({ code: "conflict" });
117
- }
120
+ await this.assertLabelAvailable({ record: input.record, existing, moved, scope });
118
121
  const hasGroup = (existing !== null && !moved) || input.record.isDefault || Boolean(await this.kernel.run(db => this.scoped({ db, input: scope }).select("id").limit(1).executeTakeFirst()));
119
122
  const saved = { ...input.record, isDefault: input.record.isDefault || !hasGroup };
120
123
  // Clear before insert/update so a partial UNIQUE default index never sees two defaults.