stitchkit 0.123.3 → 0.123.4

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/CHANGELOG.md CHANGED
@@ -15,6 +15,33 @@ additive**; the first breaking change landed in 0.10.0. Grep the file for
15
15
 
16
16
  ## [Unreleased]
17
17
 
18
+ ## [0.123.4] - 2026-11-12
19
+
20
+ ### Added
21
+
22
+ - `stitchkit/files` — **`bindUnixSocket({ path, mode }, bind)`: a unix socket that exists only
23
+ with its mode.** `bind(2)` takes a socket's rights from the umask and accepts no mode, so `chmod`
24
+ after `listen` leaves `0755` on disk until it runs, and a process watching the path sees it even
25
+ with `chmodSync` on the next line. The function narrows the umask to exactly `mode` for the one
26
+ synchronous `bind(path)` — `Bun.serve({ unix: path })` or a `node:http`/`node:net`
27
+ `listen(path)` — and restores it in `finally`. The path must be free beforehand and a socket with
28
+ exactly `mode` afterwards: a failed or late bind and a directory whose default ACL overrides the
29
+ umask are refused, a socket born with other rights is removed first. Services that each kept
30
+ their own "narrow the umask around `Bun.serve`" copy take this one; the `stitchkit/files` budget
31
+ grows by the function and `UnixSocketBinding`.
32
+
33
+ ### Fixed
34
+
35
+ - `stitchkit/server`, `stitchkit/agent-runtime/sandbox` — **a unix socket with `mode` is born with
36
+ it instead of being narrowed after it exists.** `createServer({ unix: { path, mode } })` listened
37
+ under the process umask and called `chmodSync` next: an observer in another process saw the socket
38
+ `0755` in 9 of 30 starts under umask `022`, and a readiness check that met it in that window
39
+ refused the service. The sandbox HTTP gateway did the same with `await chmod(…, 0o600)`. Both now
40
+ bind through `bindUnixSocket`; the stale-socket probe still runs before the bind, under the
41
+ normal umask. A socket the filesystem would give other rights than `mode` now fails the start
42
+ instead of being published wider.
43
+ **Affects:** `stitchkit/server` createServer(unix); `stitchkit/agent-runtime/sandbox` createBubblewrapSandboxBackend(behaviour)
44
+
18
45
  ## [0.123.3] - 2026-11-12
19
46
 
20
47
  ### Added
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox-broker.d.ts","sourceRoot":"","sources":["../../src/agent-runtime/sandbox-broker.ts"],"names":[],"mappings":"AAIA,OAAO,EAAgB,KAAK,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE7E,6FAA6F;AAC7F,wBAAsB,mBAAmB,CACvC,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,oBAAoB,EACrC,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI;;;GA2GlC"}
1
+ {"version":3,"file":"sandbox-broker.d.ts","sourceRoot":"","sources":["../../src/agent-runtime/sandbox-broker.ts"],"names":[],"mappings":"AAKA,OAAO,EAAgB,KAAK,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE7E,6FAA6F;AAC7F,wBAAsB,mBAAmB,CACvC,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,oBAAoB,EACrC,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI;;;GAoHlC"}
@@ -19,6 +19,9 @@ import {
19
19
  terminateOwnedGroup,
20
20
  startNativeCommand
21
21
  } from "../../index-gdqawggb.js";
22
+ import {
23
+ bindUnixSocket2
24
+ } from "../../index-drcjjhy1.js";
22
25
  import"../../index-kffm4r8w.js";
23
26
  import"../../index-fa53vygr.js";
24
27
  import"../../index-ww3gss55.js";
@@ -40,7 +43,7 @@ import { join as join2, posix as posix2 } from "node:path";
40
43
  import { z as z3 } from "zod";
41
44
 
42
45
  // src/agent-runtime/sandbox-broker.ts
43
- import { chmod, unlink } from "node:fs/promises";
46
+ import { unlink } from "node:fs/promises";
44
47
  import { createServer } from "node:http";
45
48
 
46
49
  // src/agent-runtime/sandbox-contract.ts
@@ -176,11 +179,20 @@ Connection: close\r
176
179
  `));
177
180
  server.requestTimeout = 30000;
178
181
  server.headersTimeout = 5000;
179
- await new Promise((resolve, reject) => {
182
+ const listening = new Promise((resolve, reject) => {
180
183
  server.once("error", reject);
181
- server.listen(socketPath, resolve);
184
+ server.once("listening", resolve);
182
185
  });
183
- await chmod(socketPath, 384);
186
+ try {
187
+ bindUnixSocket2({ path: socketPath, mode: 384 }, (path) => server.listen(path));
188
+ } catch (error) {
189
+ listening.catch(() => {
190
+ return;
191
+ });
192
+ server.close();
193
+ throw error;
194
+ }
195
+ await listening;
184
196
  return {
185
197
  abortRequests() {
186
198
  for (const controller of controllers)
@@ -5,5 +5,6 @@ export { CHUNK_SPOOL_ERROR_CODES, type ChunkSpool, type ChunkSpoolAssembly, type
5
5
  export { type WriteFileAtomicOptions, writeFileAtomic, writeFileAtomicSync, } from '../internal/atomic-file.js';
6
6
  export { AtomicFilePublicationError } from '../internal/atomic-publication.js';
7
7
  export { isAtomicStagingName, type SweepAtomicStagingOptions, sweepAtomicStaging, } from '../internal/atomic-staging.js';
8
+ export { bindUnixSocket, type UnixSocketBinding } from '../internal/unix-socket.js';
8
9
  export { type ExclusiveLock, ExclusiveLockError, type ExclusiveLockOptions, type ExclusiveLockOwner, withExclusiveLock, } from '../internal/with-exclusive-lock.js';
9
10
  //# sourceMappingURL=files.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../src/entrypoints/files.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,eAAe,EACpB,qBAAqB,EACrB,KAAK,cAAc,EACnB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EACL,yBAAyB,EACzB,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAC/B,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,uBAAuB,EACvB,KAAK,UAAU,EACf,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,KAAK,sBAAsB,EAC3B,eAAe,EACf,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EACL,mBAAmB,EACnB,KAAK,yBAAyB,EAC9B,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,KAAK,aAAa,EAClB,kBAAkB,EAClB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,iBAAiB,GAClB,MAAM,iCAAiC,CAAC"}
1
+ {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../src/entrypoints/files.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,eAAe,EACpB,qBAAqB,EACrB,KAAK,cAAc,EACnB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EACL,yBAAyB,EACzB,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAC/B,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,uBAAuB,EACvB,KAAK,UAAU,EACf,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,KAAK,sBAAsB,EAC3B,eAAe,EACf,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EACL,mBAAmB,EACnB,KAAK,yBAAyB,EAC9B,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,KAAK,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACjF,OAAO,EACL,KAAK,aAAa,EAClB,kBAAkB,EAClB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,iBAAiB,GAClB,MAAM,iCAAiC,CAAC"}
@@ -5,6 +5,9 @@ import {
5
5
  import"../index-sqc6ezrb.js";
6
6
  import"../index-bqzgaj57.js";
7
7
  import"../index-chz7c830.js";
8
+ import {
9
+ bindUnixSocket2
10
+ } from "../index-drcjjhy1.js";
8
11
  import {
9
12
  ExclusiveLockError2,
10
13
  withExclusiveLock2
@@ -268,6 +271,7 @@ export {
268
271
  ManagedFileError2 as ManagedFileError,
269
272
  ManagedFilePathSchema2 as ManagedFilePathSchema,
270
273
  ManagedFileRefSchema2 as ManagedFileRefSchema,
274
+ bindUnixSocket2 as bindUnixSocket,
271
275
  createChunkSpool,
272
276
  createManagedFileBoundary2 as createManagedFileBoundary,
273
277
  isAtomicStagingName2 as isAtomicStagingName,
@@ -60,6 +60,9 @@ import {
60
60
  import {
61
61
  bindRealtimeServer2
62
62
  } from "../index-sqkttz7z.js";
63
+ import {
64
+ bindUnixSocket2
65
+ } from "../index-drcjjhy1.js";
63
66
  import"../index-73dappvg.js";
64
67
  import {
65
68
  withDeadline
@@ -346,7 +349,7 @@ function bindSocketRegistry(server, options) {
346
349
  };
347
350
  }
348
351
  // src/server/bun.ts
349
- import { chmodSync, statSync, unlinkSync } from "node:fs";
352
+ import { statSync, unlinkSync } from "node:fs";
350
353
 
351
354
  // src/server/proxy-origin.ts
352
355
  import { z } from "zod";
@@ -437,6 +440,31 @@ function assertUnixListenConfig(config, unixPath) {
437
440
  throw new Error("[stitchkit] createServer: the Socket.IO lifecycle cannot listen on a unix socket — socket.io clients dial TCP only");
438
441
  }
439
442
  }
443
+ function listenOnUnixSocket(unix, { bunExtra, development, websocket, fetch }) {
444
+ reclaimStaleUnixSocket(unix.path);
445
+ const { reusePort, ipv6Only, http3, http2, http1, idleTimeout, ...unixExtra } = bunExtra ?? {};
446
+ const listen = (path) => websocket ? Bun.serve({
447
+ ...unixExtra,
448
+ ...development && { development },
449
+ unix: path,
450
+ websocket,
451
+ fetch
452
+ }) : Bun.serve({ ...unixExtra, ...development && { development }, unix: path, fetch });
453
+ if (unix.mode === undefined)
454
+ return listen(unix.path);
455
+ let started;
456
+ try {
457
+ return bindUnixSocket2({ path: unix.path, mode: unix.mode }, (path) => {
458
+ started = listen(path);
459
+ return started;
460
+ });
461
+ } catch (error) {
462
+ started?.stop(true).catch(() => {
463
+ return;
464
+ });
465
+ throw error;
466
+ }
467
+ }
440
468
  async function waitForRequestDrain(server) {
441
469
  while (server.pendingRequests > 0) {
442
470
  await new Promise((resolve) => setTimeout(resolve, 5));
@@ -568,22 +596,7 @@ function createServer(config) {
568
596
  return admittedFetch(normalized, server);
569
597
  };
570
598
  if (unixPath !== undefined) {
571
- reclaimStaleUnixSocket(unixPath);
572
- const { reusePort, ipv6Only, http3, http2, http1, idleTimeout, ...unixExtra } = bunExtra ?? {};
573
- runtime = trackedWebSocket ? Bun.serve({
574
- ...unixExtra,
575
- ...development && { development },
576
- unix: unixPath,
577
- websocket: trackedWebSocket,
578
- fetch
579
- }) : Bun.serve({
580
- ...unixExtra,
581
- ...development && { development },
582
- unix: unixPath,
583
- fetch
584
- });
585
- if (unixMode !== undefined)
586
- chmodSync(unixPath, unixMode);
599
+ runtime = listenOnUnixSocket({ path: unixPath, mode: unixMode }, { bunExtra, development, websocket: trackedWebSocket, fetch });
587
600
  } else {
588
601
  runtime = trackedWebSocket ? Bun.serve({
589
602
  ...bunExtra,
@@ -0,0 +1,40 @@
1
+ // src/internal/unix-socket.ts
2
+ import { lstatSync, unlinkSync } from "node:fs";
3
+ var PERMISSION_BITS = 511;
4
+ function octal(mode) {
5
+ return `0o${mode.toString(8).padStart(3, "0")}`;
6
+ }
7
+ function bindUnixSocket2(socket, bind) {
8
+ const { path, mode } = socket;
9
+ if (path.length === 0) {
10
+ throw new Error("[stitchkit] bindUnixSocket: `path` must be a non-empty socket path");
11
+ }
12
+ if (!Number.isInteger(mode) || mode < 0 || mode > PERMISSION_BITS) {
13
+ throw new Error(`[stitchkit] bindUnixSocket: \`mode\` must be permission bits 0o000–0o777, got ${String(mode)}`);
14
+ }
15
+ if (lstatSync(path, { throwIfNoEntry: false }) !== undefined) {
16
+ throw new Error(`[stitchkit] bindUnixSocket: "${path}" already exists — a socket is bound on a free path; remove a stale socket first`);
17
+ }
18
+ const previous = process.umask(~mode & PERMISSION_BITS);
19
+ let bound;
20
+ try {
21
+ bound = bind(path);
22
+ } finally {
23
+ process.umask(previous);
24
+ }
25
+ const stats = lstatSync(path, { throwIfNoEntry: false });
26
+ if (stats === undefined) {
27
+ throw new Error(`[stitchkit] bindUnixSocket: no socket at "${path}" when bind returned — the listen failed (its error arrives on the server's error event) or does not bind synchronously inside the call`);
28
+ }
29
+ if (!stats.isSocket()) {
30
+ throw new Error(`[stitchkit] bindUnixSocket: "${path}" is not a socket after bind — the bind must listen on this path`);
31
+ }
32
+ const born = stats.mode & PERMISSION_BITS;
33
+ if (born !== mode) {
34
+ unlinkSync(path);
35
+ throw new Error(`[stitchkit] bindUnixSocket: socket "${path}" was born ${octal(born)} instead of ${octal(mode)} — something other than the umask sets the rights in this directory (a default ACL?); the socket was removed`);
36
+ }
37
+ return bound;
38
+ }
39
+
40
+ export { bindUnixSocket2 };
@@ -0,0 +1,28 @@
1
+ /** Where a unix socket is bound and the exact permission bits it is born with. */
2
+ export interface UnixSocketBinding {
3
+ readonly path: string;
4
+ /** Permission bits `0o000`–`0o777`; `0o600` when access to the socket is the credential. */
5
+ readonly mode: number;
6
+ }
7
+ /**
8
+ * Bind a unix socket that exists only with `mode`, never with wider rights first.
9
+ *
10
+ * `bind(2)` takes a socket file's permissions from the process umask and accepts no mode, so a
11
+ * `chmod` after the bind leaves the umask rights on disk until it runs, and a process watching the
12
+ * path sees them even with `chmodSync` on the next line. The umask is narrowed to exactly
13
+ * `~mode` for the one synchronous `bind(path)` call and restored in `finally`, before any other
14
+ * JavaScript runs.
15
+ *
16
+ * The umask is process-wide. A file another thread creates during that call is born at most as
17
+ * permissive as the socket — narrower, never wider — and work that must keep the normal umask (a
18
+ * child process, a liveness probe) runs before the call, not inside `bind`.
19
+ *
20
+ * The path must be free before the call, so whatever stands there afterwards was created by it;
21
+ * a stale socket is the caller's to remove first. After `bind` the path must be a socket with
22
+ * exactly `mode`. A bind that failed — Node and Bun report a `listen` error asynchronously, on the
23
+ * server's `error` event — or completes later than the call, and a directory whose default ACL
24
+ * overrides the umask, all fail here; a socket that was born with other rights is unlinked first,
25
+ * so no client reaches it by path. The listener `bind` started is the caller's to stop.
26
+ */
27
+ export declare function bindUnixSocket<T>(socket: UnixSocketBinding, bind: (path: string) => T): T;
28
+ //# sourceMappingURL=unix-socket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unix-socket.d.ts","sourceRoot":"","sources":["../../src/internal/unix-socket.ts"],"names":[],"mappings":"AAEA,kFAAkF;AAClF,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,4FAA4F;IAC5F,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAQD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,EAAE,iBAAiB,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,CAAC,GAAG,CAAC,CAyCzF"}
@@ -16,10 +16,11 @@ type BunDevelopmentOptions = BunServeOptions extends {
16
16
  } ? T : never;
17
17
  export type ServerPassthrough = Omit<BunServeOptions, 'fetch' | 'port' | 'hostname' | 'unix' | 'routes' | 'websocket' | 'development'>;
18
18
  /**
19
- * Unix domain socket listener. The plain-string form binds the path as-is;
20
- * the object form additionally tightens the socket file mode after listen —
21
- * `mode: 0o600` is the right choice when access to the socket IS the
22
- * credential (a local daemon whose only auth is filesystem permission).
19
+ * Unix domain socket listener. The plain-string form binds the path under the
20
+ * process umask; the object form binds it with exactly `mode` from birth
21
+ * (`bindUnixSocket` from `stitchkit/files`) — `mode: 0o600` is the right choice
22
+ * when access to the socket IS the credential (a local daemon whose only auth
23
+ * is filesystem permission).
23
24
  */
24
25
  export type UnixListenConfig = string | {
25
26
  path: string;
@@ -1 +1 @@
1
- {"version":3,"file":"bun.d.ts","sourceRoot":"","sources":["../../src/server/bun.ts"],"names":[],"mappings":"AAGA,OAAO,EAAqB,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAEL,KAAK,mBAAmB,EAEzB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,KAAK,EACV,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,QAAQ,EACR,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB,yEAAyE;AACzE,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;AACrD,MAAM,MAAM,WAAW,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;AAC9C,MAAM,MAAM,kBAAkB,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;AAC5D,MAAM,MAAM,eAAe,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AACtD,MAAM,MAAM,mBAAmB,GAAG,gBAAgB,CAAC,SAAS,CAAC,CAAC;AAC9D,MAAM,MAAM,gBAAgB,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC;AAExD,KAAK,eAAe,GAAG,UAAU,CAAC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AACvD,KAAK,oBAAoB,GAAG,GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAC1D,KAAK,qBAAqB,GAAG,eAAe,SAAS;IAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CAAA;CAAE,GAAG,CAAC,GAAG,KAAK,CAAC;AAE3F,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAClC,eAAe,EACf,OAAO,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,WAAW,GAAG,aAAa,CAChF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAExE,8EAA8E;AAC9E,MAAM,WAAW,eAAgB,SAAQ,gBAAgB,EAAE,mBAAmB;IAC5E;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;OAOG;IACH,IAAI,CAAC,EAAE,gBAAgB,CAAC;IACxB,SAAS,CAAC,EAAE,oBAAoB,CAAC;IACjC,iGAAiG;IACjG,MAAM,CAAC,EAAE,uBAAuB,CAAC;IACjC,WAAW,CAAC,EAAE,qBAAqB,CAAC;IACpC,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED,MAAM,MAAM,eAAe,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;AA+F7D,wBAAgB,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,eAAe,CAqMrE"}
1
+ {"version":3,"file":"bun.d.ts","sourceRoot":"","sources":["../../src/server/bun.ts"],"names":[],"mappings":"AAIA,OAAO,EAAqB,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAEL,KAAK,mBAAmB,EAEzB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,KAAK,EACV,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,QAAQ,EACR,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB,yEAAyE;AACzE,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;AACrD,MAAM,MAAM,WAAW,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;AAC9C,MAAM,MAAM,kBAAkB,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;AAC5D,MAAM,MAAM,eAAe,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AACtD,MAAM,MAAM,mBAAmB,GAAG,gBAAgB,CAAC,SAAS,CAAC,CAAC;AAC9D,MAAM,MAAM,gBAAgB,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC;AAExD,KAAK,eAAe,GAAG,UAAU,CAAC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AACvD,KAAK,oBAAoB,GAAG,GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAC1D,KAAK,qBAAqB,GAAG,eAAe,SAAS;IAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CAAA;CAAE,GAAG,CAAC,GAAG,KAAK,CAAC;AAE3F,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAClC,eAAe,EACf,OAAO,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,WAAW,GAAG,aAAa,CAChF,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAExE,8EAA8E;AAC9E,MAAM,WAAW,eAAgB,SAAQ,gBAAgB,EAAE,mBAAmB;IAC5E;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;OAOG;IACH,IAAI,CAAC,EAAE,gBAAgB,CAAC;IACxB,SAAS,CAAC,EAAE,oBAAoB,CAAC;IACjC,iGAAiG;IACjG,MAAM,CAAC,EAAE,uBAAuB,CAAC;IACjC,WAAW,CAAC,EAAE,qBAAqB,CAAC;IACpC,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED,MAAM,MAAM,eAAe,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;AAiJ7D,wBAAgB,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,eAAe,CA6KrE"}
package/llms/files.txt CHANGED
@@ -34,6 +34,7 @@ available from `stitchkit/contract`.
34
34
  | `sweepAtomicStaging` / `SweepAtomicStagingOptions` | function / _type_ | remove abandoned staging files from one `directory`: only regular files matching `isAtomicStagingName` and older than the required `olderThanMs`, never following a symlink or entering a subdirectory; stops on `signal`; returns the removed names, `[]` for a `directory` that does not exist |
35
35
  | `withExclusiveLock` / `ExclusiveLockOptions` / `ExclusiveLock` / `ExclusiveLockOwner` | function / _type_ | run work under an exclusive lock between processes — a file recording its owner (pid, host, machine identity, time and nullable kernel process identity); waits up to `timeoutMs` (default 10 s) and stops on `signal`; a dead owner on this machine is taken over, a live, slow or foreign one never is; a lock recorded by this very process is held only while one of its descriptors is open on it, so the lock an earlier image of the same PID left (`bun --watch` restarts in place) is taken over at once; the lock is published with its owner already recorded (temporary file plus hard link), so a stalled holder is never displaced; a legacy empty lock file is taken by age only when `ownerlessGraceMs` is a number (default `null`: never; an abandoned empty reclaim guard is taken after 5 000 ms unless a value is set); exact `mode` is independent of umask; shared readers need a common group and traversable directories |
36
36
  | `ExclusiveLockError` | class | `LOCK_TIMEOUT` naming the resource and its holder, or `LOCK_ABORTED` with the signal's reason |
37
+ | `bindUnixSocket` / `UnixSocketBinding` | function / _type_ | bind a unix socket that exists only with `mode` (`0o000`–`0o777`), never wider first: the umask is narrowed for the one synchronous `bind(path)` (`Bun.serve({ unix })`, `node:http`/`node:net` `listen(path)`) and restored before any other JavaScript; the path must be free beforehand and a socket with exactly `mode` afterwards, else it refuses (a socket born with other rights is removed) — [guide](../guide/native-io.md#a-unix-socket-private-from-birth) |
37
38
  | `createChunkSpool` | function | the server half of a chunked upload: parts on disk under `owner` + client-minted `uploadId`, each with a size+sha256 receipt; idempotent `open` and `put`, the first writer of a part wins across processes, `assemble` in order once every part is in, `sweep` of untouched uploads — [guide](../guide/client.md#chunked-uploads) |
38
39
  | `ChunkSpool` / `ChunkSpoolConfig` / `ChunkSpoolKey` / `ChunkSpoolOpen` / `ChunkSpoolPart` / `ChunkSpoolAssembly` | _type_ | the spool, its directory, part size, file limit, meta schema and age; an upload's key; its declaration; one part; the assembled parts with a concatenating `stream()` |
39
40
  | `ChunkSpoolErrorCode` | _type_ | the `AppError` codes a spool refuses with, each with its 4xx status: `UPLOAD_INVALID`, `UPLOAD_TOO_LARGE`, `UPLOAD_NOT_FOUND`, `UPLOAD_CONFLICT`, `UPLOAD_CHUNK_OUT_OF_RANGE`, `UPLOAD_CHUNK_SIZE`, `UPLOAD_INCOMPLETE` |
@@ -11,6 +11,139 @@ Parts of this slice:
11
11
  # Guide: Native IO (docs/guide/native-io.md) (continued)
12
12
  ==============================================================================
13
13
 
14
+ ## Public native packaging
15
+
16
+ Custom archives and installers use `stitchkit/files/packaging` at **build time**.
17
+ `createNativePackaging` resolves the installed version and target addon, reads the addon once and
18
+ checks it against the size and SHA256 that Stitchkit published in its `native-assets.json` when the
19
+ package was built. A ready asset carries those verified `bytes` with the published `size` and
20
+ `sha256`; its Bun-compatible plugin integrates the same bytes with the same lazy native loader.
21
+ Each call reads and hashes the selected addons, so call it once per build and reuse the result.
22
+ The leaf is evolving. It requires no optional peer or Bun ambient declarations for Node imports.
23
+ Calling it must happen in a process that runs it from its installed package: it locates the
24
+ package's `native-assets.json` beside its own file and throws `Native packaging must run from its
25
+ installed Stitchkit package` anywhere else, such as inside an application's runtime artifact.
26
+ Importing the leaf is side-effect free (it loads no addon and reads no file), so a module that
27
+ both builds and is bundled may import it; only the call has to stay in the build step.
28
+
29
+ ```ts
30
+ import { createNativePackaging } from 'stitchkit/files/packaging'
31
+ import { mkdirSync, writeFileSync } from 'node:fs'
32
+ import { dirname, join } from 'node:path'
33
+
34
+ const native = createNativePackaging({
35
+ platform: 'darwin', architecture: 'arm64', delivery: 'companion',
36
+ entryPath: 'app/native.js', assetPath: 'addons/owner.node',
37
+ })
38
+ if (native.state !== 'ready') throw new Error(native.code)
39
+ const result = await Bun.build({
40
+ entrypoints: ['src/native.ts'], target: 'node', format: 'esm',
41
+ outdir: 'dist', naming: { entry: 'app/native.js' }, splitting: false,
42
+ plugins: [native.plugin],
43
+ })
44
+ if (!result.success) throw new AggregateError(result.logs, 'Build failed')
45
+ // Preserve every result.outputs file under dist, then write the verified companion bytes.
46
+ for (const asset of native.assets) {
47
+ const destination = join('dist', asset.outputPath)
48
+ mkdirSync(dirname(destination), { recursive: true })
49
+ writeFileSync(destination, asset.bytes)
50
+ }
51
+ ```
52
+
53
+ In companion delivery, `entryPath` and `assetPath` are relative paths inside the application's output root, without
54
+ absolute paths, traversal or overlapping file/directory paths. `assetPath` may contain `[hash]`,
55
+ which becomes the first 16 hex digits of that addon's published SHA256: the digest is known before
56
+ the build, so `addons/darwin-arm64-[hash].node` gives two installed versions of the package
57
+ different companion names, and the loader requires exactly that name. It is the only template an
58
+ addon path accepts. `entryPath` is fixed, without
59
+ Bun naming templates such as `[dir]` or `[name]`. Companion JS builds require one entry, no splitting,
60
+ and `naming.entry` exactly matching `entryPath`; the plugin rejects a mismatching layout.
61
+ Choose any application layout; the framework does not prescribe an app directory or installer.
62
+ The plugin packages the loader of the installation it was created from. A build whose entry
63
+ imports another `stitchkit` installation — another version, or the same version under another
64
+ path, as when a build tool carries its own copy — fails with an error naming both versions and
65
+ roots: that installation's loader would refuse the addon at run time, so the artifact is never
66
+ written. Call `createNativePackaging` from the `stitchkit` the entry imports.
67
+ Keep every bundler output and write `asset.bytes`; never read the addon from `node_modules` a
68
+ second time. An installed addon whose size or SHA256 differs from the published manifest refuses
69
+ with `mismatch` / `NATIVE_ASSET_DIGEST_MISMATCH`, so a file substituted after installation never
70
+ reaches an artifact. Archive the complete output directory with an integrity manifest that records
71
+ `asset.sha256`, unpack to a clean directory, verify the same hashes there, and run offline without
72
+ the build tree or `node_modules`. The published digest ties the bytes to the package Stitchkit
73
+ built; the package itself is only as trusted as its tarball (the lockfile integrity of the install).
74
+ Signature and trust policy remain application-owned.
75
+
76
+ One JS artifact can run on both Darwin architectures; change only the packaging inputs:
77
+
78
+ ```ts
79
+ const native = createNativePackaging({
80
+ platform: 'darwin', architecture: ['arm64', 'x64'], delivery: 'companion',
81
+ entryPath: 'app/native.js',
82
+ assetPath: { arm64: 'addons/arm.node', x64: 'addons/intel.node' },
83
+ })
84
+ ```
85
+
86
+ Use the same single plugin and write loop above. A single-target loader deliberately refuses the
87
+ other architecture; two competing plugins cannot produce a universal loader. The array form
88
+ requires exactly one distinct output path per declared target. A ready result carries the target
89
+ array and both verified assets with their published digests; `NativePackagingOptions<true>` /
90
+ `NativePackagingResult<true>` describe this form when explicitly annotating variables.
91
+ The loader selects only `process.arch`: a missing or wrong-architecture selected addon refuses,
92
+ even when the other valid addon is present. Linux runtime imports remain lazy and use Linux
93
+ process primitives without loading Darwin assets. Qualify the exact same JS bytes on real
94
+ Darwin arm64 and x64 machines, with both companions preserved through archive delivery.
95
+ Build-machine architecture and cross-build success cannot establish universal native support.
96
+
97
+ For a standalone executable use `delivery: 'embedded'` and its plugin in `Bun.build` with
98
+ `compile`. An executable carries the addon inside itself, so this form names no `entryPath` or
99
+ `assetPath`; passing one is a type error and a schema refusal, never silently ignored:
100
+
101
+ ```ts
102
+ const native = createNativePackaging({
103
+ platform: 'darwin', architecture: 'arm64', delivery: 'embedded',
104
+ })
105
+ if (native.state !== 'ready') throw new Error(native.code)
106
+ const result = await Bun.build({
107
+ entrypoints: ['src/cli.ts'], minify: true,
108
+ compile: { target: 'bun-darwin-arm64', outfile: 'dist/cli' },
109
+ plugins: [native.plugin],
110
+ })
111
+ if (!result.success) throw new AggregateError(result.logs, 'Build failed')
112
+ ```
113
+
114
+ Bun embeds the selected addon from the verified bytes the plugin holds, not from a second read of
115
+ the file, and the executable loads it from `/$bunfs/root/darwin-arm64-<hash>.node`. Its `assets`
116
+ (`NativePackagingEmbeddedAsset`: `bytes`, `size`, `sha256`) identify those bytes and their
117
+ published digest for qualification; there is nothing to write beside the executable.
118
+ Cross-builds must select the requested architecture explicitly; the artifact must run on that target.
119
+ The installed package must contain that target's addon. No automatic fallback/downgrade occurs.
120
+
121
+ `platform` is the closed set of platforms with native addons, today `'darwin'`: another name is a
122
+ type error and a schema refusal that throws, so pass the literal (or narrow `process.platform`
123
+ with `=== 'darwin'`) rather than a free string. The API returns `unsupported` /
124
+ `NATIVE_TARGET_UNSUPPORTED` for an unsupported architecture, `missing` / `NATIVE_ASSET_MISSING` for
125
+ an addon the package does not publish or whose file is gone, and `mismatch` /
126
+ `NATIVE_ASSET_DIGEST_MISMATCH` for an addon whose bytes differ from the published size or SHA256.
127
+ A `mismatch` names the first differing `architecture` and carries `expected` (the published
128
+ `{ size, sha256 }`) and `actual` (the installed file's size and the SHA256 of the bytes read), so
129
+ a build log can tell a truncated copy from a substituted one:
130
+
131
+ ```ts
132
+ if (native.state === 'mismatch')
133
+ throw new Error(
134
+ `${native.architecture} addon: expected ${native.expected.size} bytes ` +
135
+ `${native.expected.sha256}, found ${native.actual.size} bytes ${native.actual.sha256}`,
136
+ )
137
+ ```
138
+
139
+ Portable libraries
140
+ and Linux builds use their normal build, without a Darwin plugin; merely importing the build leaf
141
+ loads no addon.
142
+ Malformed inputs, a manifest whose `formatVersion` is not 2 and other IO errors throw before packaging.
143
+ A missing or corrupt companion at runtime yields the native `unavailable` result with the safe
144
+ stage and code from the observer; it never certifies a dead owner. Preserve the raw cause internally.
145
+ The plugin does not parse consumer JS or establish a second runtime native implementation.
146
+
14
147
  ## A client as one self-contained file
15
148
 
16
149
  A package that owns a server usually ships a typed client for it, and the client's consumers
package/llms/process.txt CHANGED
@@ -96,6 +96,43 @@ filesystems or survival of a power loss; the disk state is whatever the filesyst
96
96
  `createManagedFileBoundary.write(..., { durable: true })` uses the same publish owner and parent sync;
97
97
  its create stays a create, and `replace: true` allows replacement explicitly.
98
98
 
99
+ ## A unix socket private from birth
100
+
101
+ When access to a socket is the credential, the socket must never exist with wider rights. `bind(2)`
102
+ accepts no mode — a socket file takes its rights from the process umask — so `chmod` after `listen`
103
+ leaves the umask rights (`0755` under `022`) on disk until it runs, and a process watching the path
104
+ sees them even when `chmodSync` is the very next line. `bindUnixSocket` binds under a umask narrowed
105
+ to exactly `mode` for one synchronous call and restores it before any other JavaScript runs:
106
+
107
+ ```ts
108
+ import { createServer } from 'node:http'
109
+ import { bindUnixSocket } from 'stitchkit/files'
110
+
111
+ // Bun
112
+ const server = bindUnixSocket({ path: '/run/app/door.sock', mode: 0o600 }, (path) =>
113
+ Bun.serve({ unix: path, fetch: () => new Response('ok') }),
114
+ )
115
+
116
+ // Node (and Bun's node:http) — the bind happens inside `listen`; its error arrives on 'error'
117
+ const door = createServer(handler)
118
+ bindUnixSocket({ path: '/run/app/door.sock', mode: 0o600 }, (path) => door.listen(path))
119
+ ```
120
+
121
+ `createServer({ unix: { path, mode } })` from `stitchkit/server` binds through the same function.
122
+
123
+ - The path must be free: whatever stands there after the call was created by it. Remove a stale
124
+ socket first (`createServer` probes and reclaims one); an existing file is refused before anything
125
+ binds.
126
+ - After the call the path must be a socket with exactly `mode`, or the call throws. A bind that
127
+ failed (Node and Bun report a `listen` error asynchronously), one that binds later than the call,
128
+ and a directory whose default ACL — not the umask — decides the rights all end here; a socket born
129
+ with other rights is removed first, so no client reaches it by path. The listener your `bind`
130
+ started is yours to stop.
131
+ - The umask is process-wide. A file another thread creates during the call is born at most as
132
+ permissive as the socket — narrower, never wider. Work that needs the normal umask, a child
133
+ process above all, runs before the call, not inside `bind`. A Node worker thread cannot set the
134
+ umask and gets that error.
135
+
99
136
  ## Strict reads
100
137
 
101
138
  ```ts
@@ -635,136 +672,3 @@ no recognized native error code, the stage stays `load`; the loader never infers
635
672
 
636
673
  This delivery removes a runtime kernel installation; it does not remove the build-time
637
674
  Stitchkit installation or create an independent lightweight npm package.
638
-
639
- ## Public native packaging
640
-
641
- Custom archives and installers use `stitchkit/files/packaging` at **build time**.
642
- `createNativePackaging` resolves the installed version and target addon, reads the addon once and
643
- checks it against the size and SHA256 that Stitchkit published in its `native-assets.json` when the
644
- package was built. A ready asset carries those verified `bytes` with the published `size` and
645
- `sha256`; its Bun-compatible plugin integrates the same bytes with the same lazy native loader.
646
- Each call reads and hashes the selected addons, so call it once per build and reuse the result.
647
- The leaf is evolving. It requires no optional peer or Bun ambient declarations for Node imports.
648
- Calling it must happen in a process that runs it from its installed package: it locates the
649
- package's `native-assets.json` beside its own file and throws `Native packaging must run from its
650
- installed Stitchkit package` anywhere else, such as inside an application's runtime artifact.
651
- Importing the leaf is side-effect free (it loads no addon and reads no file), so a module that
652
- both builds and is bundled may import it; only the call has to stay in the build step.
653
-
654
- ```ts
655
- import { createNativePackaging } from 'stitchkit/files/packaging'
656
- import { mkdirSync, writeFileSync } from 'node:fs'
657
- import { dirname, join } from 'node:path'
658
-
659
- const native = createNativePackaging({
660
- platform: 'darwin', architecture: 'arm64', delivery: 'companion',
661
- entryPath: 'app/native.js', assetPath: 'addons/owner.node',
662
- })
663
- if (native.state !== 'ready') throw new Error(native.code)
664
- const result = await Bun.build({
665
- entrypoints: ['src/native.ts'], target: 'node', format: 'esm',
666
- outdir: 'dist', naming: { entry: 'app/native.js' }, splitting: false,
667
- plugins: [native.plugin],
668
- })
669
- if (!result.success) throw new AggregateError(result.logs, 'Build failed')
670
- // Preserve every result.outputs file under dist, then write the verified companion bytes.
671
- for (const asset of native.assets) {
672
- const destination = join('dist', asset.outputPath)
673
- mkdirSync(dirname(destination), { recursive: true })
674
- writeFileSync(destination, asset.bytes)
675
- }
676
- ```
677
-
678
- In companion delivery, `entryPath` and `assetPath` are relative paths inside the application's output root, without
679
- absolute paths, traversal or overlapping file/directory paths. `assetPath` may contain `[hash]`,
680
- which becomes the first 16 hex digits of that addon's published SHA256: the digest is known before
681
- the build, so `addons/darwin-arm64-[hash].node` gives two installed versions of the package
682
- different companion names, and the loader requires exactly that name. It is the only template an
683
- addon path accepts. `entryPath` is fixed, without
684
- Bun naming templates such as `[dir]` or `[name]`. Companion JS builds require one entry, no splitting,
685
- and `naming.entry` exactly matching `entryPath`; the plugin rejects a mismatching layout.
686
- Choose any application layout; the framework does not prescribe an app directory or installer.
687
- The plugin packages the loader of the installation it was created from. A build whose entry
688
- imports another `stitchkit` installation — another version, or the same version under another
689
- path, as when a build tool carries its own copy — fails with an error naming both versions and
690
- roots: that installation's loader would refuse the addon at run time, so the artifact is never
691
- written. Call `createNativePackaging` from the `stitchkit` the entry imports.
692
- Keep every bundler output and write `asset.bytes`; never read the addon from `node_modules` a
693
- second time. An installed addon whose size or SHA256 differs from the published manifest refuses
694
- with `mismatch` / `NATIVE_ASSET_DIGEST_MISMATCH`, so a file substituted after installation never
695
- reaches an artifact. Archive the complete output directory with an integrity manifest that records
696
- `asset.sha256`, unpack to a clean directory, verify the same hashes there, and run offline without
697
- the build tree or `node_modules`. The published digest ties the bytes to the package Stitchkit
698
- built; the package itself is only as trusted as its tarball (the lockfile integrity of the install).
699
- Signature and trust policy remain application-owned.
700
-
701
- One JS artifact can run on both Darwin architectures; change only the packaging inputs:
702
-
703
- ```ts
704
- const native = createNativePackaging({
705
- platform: 'darwin', architecture: ['arm64', 'x64'], delivery: 'companion',
706
- entryPath: 'app/native.js',
707
- assetPath: { arm64: 'addons/arm.node', x64: 'addons/intel.node' },
708
- })
709
- ```
710
-
711
- Use the same single plugin and write loop above. A single-target loader deliberately refuses the
712
- other architecture; two competing plugins cannot produce a universal loader. The array form
713
- requires exactly one distinct output path per declared target. A ready result carries the target
714
- array and both verified assets with their published digests; `NativePackagingOptions<true>` /
715
- `NativePackagingResult<true>` describe this form when explicitly annotating variables.
716
- The loader selects only `process.arch`: a missing or wrong-architecture selected addon refuses,
717
- even when the other valid addon is present. Linux runtime imports remain lazy and use Linux
718
- process primitives without loading Darwin assets. Qualify the exact same JS bytes on real
719
- Darwin arm64 and x64 machines, with both companions preserved through archive delivery.
720
- Build-machine architecture and cross-build success cannot establish universal native support.
721
-
722
- For a standalone executable use `delivery: 'embedded'` and its plugin in `Bun.build` with
723
- `compile`. An executable carries the addon inside itself, so this form names no `entryPath` or
724
- `assetPath`; passing one is a type error and a schema refusal, never silently ignored:
725
-
726
- ```ts
727
- const native = createNativePackaging({
728
- platform: 'darwin', architecture: 'arm64', delivery: 'embedded',
729
- })
730
- if (native.state !== 'ready') throw new Error(native.code)
731
- const result = await Bun.build({
732
- entrypoints: ['src/cli.ts'], minify: true,
733
- compile: { target: 'bun-darwin-arm64', outfile: 'dist/cli' },
734
- plugins: [native.plugin],
735
- })
736
- if (!result.success) throw new AggregateError(result.logs, 'Build failed')
737
- ```
738
-
739
- Bun embeds the selected addon from the verified bytes the plugin holds, not from a second read of
740
- the file, and the executable loads it from `/$bunfs/root/darwin-arm64-<hash>.node`. Its `assets`
741
- (`NativePackagingEmbeddedAsset`: `bytes`, `size`, `sha256`) identify those bytes and their
742
- published digest for qualification; there is nothing to write beside the executable.
743
- Cross-builds must select the requested architecture explicitly; the artifact must run on that target.
744
- The installed package must contain that target's addon. No automatic fallback/downgrade occurs.
745
-
746
- `platform` is the closed set of platforms with native addons, today `'darwin'`: another name is a
747
- type error and a schema refusal that throws, so pass the literal (or narrow `process.platform`
748
- with `=== 'darwin'`) rather than a free string. The API returns `unsupported` /
749
- `NATIVE_TARGET_UNSUPPORTED` for an unsupported architecture, `missing` / `NATIVE_ASSET_MISSING` for
750
- an addon the package does not publish or whose file is gone, and `mismatch` /
751
- `NATIVE_ASSET_DIGEST_MISMATCH` for an addon whose bytes differ from the published size or SHA256.
752
- A `mismatch` names the first differing `architecture` and carries `expected` (the published
753
- `{ size, sha256 }`) and `actual` (the installed file's size and the SHA256 of the bytes read), so
754
- a build log can tell a truncated copy from a substituted one:
755
-
756
- ```ts
757
- if (native.state === 'mismatch')
758
- throw new Error(
759
- `${native.architecture} addon: expected ${native.expected.size} bytes ` +
760
- `${native.expected.sha256}, found ${native.actual.size} bytes ${native.actual.sha256}`,
761
- )
762
- ```
763
-
764
- Portable libraries
765
- and Linux builds use their normal build, without a Darwin plugin; merely importing the build leaf
766
- loads no addon.
767
- Malformed inputs, a manifest whose `formatVersion` is not 2 and other IO errors throw before packaging.
768
- A missing or corrupt companion at runtime yields the native `unavailable` result with the safe
769
- stage and code from the observer; it never certifies a dead owner. Preserve the raw cause internally.
770
- The plugin does not parse consumer JS or establish a second runtime native implementation.
package/llms/server.5.txt CHANGED
@@ -71,7 +71,7 @@ Also re-exports the error helpers from `stitchkit/contract`.
71
71
  | `BunServerConfig` | _type_ | config for `createServer` (Bun); `unix` listens on a unix domain socket (mutually exclusive with `port`/`hostname`) — [details](../guide/server.md#local-daemon-over-a-unix-socket) |
72
72
  | `defineRequestIngress` / `RequestIngress` / `RequestIngressSource` | function / _type_ | a typed key the code that builds a `Request` attaches a value to (`attach(request, value)`) and an endpoint, `authorize`, `beforeHandle` or `onError` reads from its `ctx` (`from(ctx)`); a header, `clone()` and `new Request(request)` carry nothing, a second `attach` is refused, and `ctx.req` is the very request the handler received — [guide](../guide/server.md#request-attributes-from-the-ingress) |
73
73
  | `ProxyOriginConfig` | _type_ | explicit real-peer trust for Bun `createServer({ proxyOrigin })`; strict external-scheme normalization before composition — [details](../guide/server.md#external-origin-behind-a-trusted-proxy) |
74
- | `UnixListenConfig` | _type_ | unix listener — a socket path, or `{ path, mode }` to tighten the file mode after listen |
74
+ | `UnixListenConfig` | _type_ | unix listener — a socket path bound under the process umask, or `{ path, mode }` for a socket born with exactly `mode` (`bindUnixSocket`) |
75
75
  | `BunServerHandle` | _type_ | managed Bun handle (`url`, `port`, `runtime`, `status`, `shutdown`) |
76
76
  | `ManagedServerHandle` | _type_ | shared lifecycle shape generic over the runtime escape hatch |
77
77
  | `ShutdownOptionsSchema` / `ShutdownOptions` | schema / _type_ | HTTP/application grace, a separate WebSocket close-handshake bound, bounded forced-completion timeout, retry hint and optional external abort signal |
package/llms/server.txt CHANGED
@@ -398,11 +398,14 @@ bind error of the loser). A regular file at the path, another user's socket, or
398
398
  a live listener each fail with a specific error instead of being unlinked. A
399
399
  clean `server.shutdown()` removes the file.
400
400
 
401
- `mode` tightens the socket file permissions after listen. Bun creates the file
402
- `0755` under a normal umask — since `connect(2)` requires *write* permission
403
- that is already owner-only in practice — but when access to the socket **is**
404
- the credential, set `mode: 0o600` explicitly and let the filesystem be the
405
- policy. The Socket.IO lifecycle (`socket`) cannot mount on a unix listener
401
+ `mode` is the socket's permission from birth: the socket is bound under a umask
402
+ narrowed to exactly that mode, so no other process ever sees it wider — a
403
+ `chmod` after listen leaves the umask rights on disk until it runs
404
+ ([`bindUnixSocket`](native-io.md#a-unix-socket-private-from-birth)). Without
405
+ `mode` Bun creates the file `0755` under a normal umask — since `connect(2)`
406
+ requires *write* permission that is already owner-only in practice — but when
407
+ access to the socket **is** the credential, set `mode: 0o600` explicitly and let
408
+ the filesystem be the policy. The Socket.IO lifecycle (`socket`) cannot mount on a unix listener
406
409
  (socket.io clients dial TCP only — construction error); Bun's own WebSocket
407
410
  client cannot dial a unix path either. Unix listeners are Bun-only: `srvx`
408
411
  resolves a numeric port unconditionally, so `stitchkit/node` does not offer
package/llms-full.txt CHANGED
@@ -1650,11 +1650,14 @@ bind error of the loser). A regular file at the path, another user's socket, or
1650
1650
  a live listener each fail with a specific error instead of being unlinked. A
1651
1651
  clean `server.shutdown()` removes the file.
1652
1652
 
1653
- `mode` tightens the socket file permissions after listen. Bun creates the file
1654
- `0755` under a normal umask — since `connect(2)` requires *write* permission
1655
- that is already owner-only in practice — but when access to the socket **is**
1656
- the credential, set `mode: 0o600` explicitly and let the filesystem be the
1657
- policy. The Socket.IO lifecycle (`socket`) cannot mount on a unix listener
1653
+ `mode` is the socket's permission from birth: the socket is bound under a umask
1654
+ narrowed to exactly that mode, so no other process ever sees it wider — a
1655
+ `chmod` after listen leaves the umask rights on disk until it runs
1656
+ ([`bindUnixSocket`](native-io.md#a-unix-socket-private-from-birth)). Without
1657
+ `mode` Bun creates the file `0755` under a normal umask — since `connect(2)`
1658
+ requires *write* permission that is already owner-only in practice — but when
1659
+ access to the socket **is** the credential, set `mode: 0o600` explicitly and let
1660
+ the filesystem be the policy. The Socket.IO lifecycle (`socket`) cannot mount on a unix listener
1658
1661
  (socket.io clients dial TCP only — construction error); Bun's own WebSocket
1659
1662
  client cannot dial a unix path either. Unix listeners are Bun-only: `srvx`
1660
1663
  resolves a numeric port unconditionally, so `stitchkit/node` does not offer
@@ -9093,6 +9096,43 @@ filesystems or survival of a power loss; the disk state is whatever the filesyst
9093
9096
  `createManagedFileBoundary.write(..., { durable: true })` uses the same publish owner and parent sync;
9094
9097
  its create stays a create, and `replace: true` allows replacement explicitly.
9095
9098
 
9099
+ ## A unix socket private from birth
9100
+
9101
+ When access to a socket is the credential, the socket must never exist with wider rights. `bind(2)`
9102
+ accepts no mode — a socket file takes its rights from the process umask — so `chmod` after `listen`
9103
+ leaves the umask rights (`0755` under `022`) on disk until it runs, and a process watching the path
9104
+ sees them even when `chmodSync` is the very next line. `bindUnixSocket` binds under a umask narrowed
9105
+ to exactly `mode` for one synchronous call and restores it before any other JavaScript runs:
9106
+
9107
+ ```ts
9108
+ import { createServer } from 'node:http'
9109
+ import { bindUnixSocket } from 'stitchkit/files'
9110
+
9111
+ // Bun
9112
+ const server = bindUnixSocket({ path: '/run/app/door.sock', mode: 0o600 }, (path) =>
9113
+ Bun.serve({ unix: path, fetch: () => new Response('ok') }),
9114
+ )
9115
+
9116
+ // Node (and Bun's node:http) — the bind happens inside `listen`; its error arrives on 'error'
9117
+ const door = createServer(handler)
9118
+ bindUnixSocket({ path: '/run/app/door.sock', mode: 0o600 }, (path) => door.listen(path))
9119
+ ```
9120
+
9121
+ `createServer({ unix: { path, mode } })` from `stitchkit/server` binds through the same function.
9122
+
9123
+ - The path must be free: whatever stands there after the call was created by it. Remove a stale
9124
+ socket first (`createServer` probes and reclaims one); an existing file is refused before anything
9125
+ binds.
9126
+ - After the call the path must be a socket with exactly `mode`, or the call throws. A bind that
9127
+ failed (Node and Bun report a `listen` error asynchronously), one that binds later than the call,
9128
+ and a directory whose default ACL — not the umask — decides the rights all end here; a socket born
9129
+ with other rights is removed first, so no client reaches it by path. The listener your `bind`
9130
+ started is yours to stop.
9131
+ - The umask is process-wide. A file another thread creates during the call is born at most as
9132
+ permissive as the socket — narrower, never wider. Work that needs the normal umask, a child
9133
+ process above all, runs before the call, not inside `bind`. A Node worker thread cannot set the
9134
+ umask and gets that error.
9135
+
9096
9136
  ## Strict reads
9097
9137
 
9098
9138
  ```ts
@@ -23511,7 +23551,7 @@ Also re-exports the error helpers from `stitchkit/contract`.
23511
23551
  | `BunServerConfig` | _type_ | config for `createServer` (Bun); `unix` listens on a unix domain socket (mutually exclusive with `port`/`hostname`) — [details](../guide/server.md#local-daemon-over-a-unix-socket) |
23512
23552
  | `defineRequestIngress` / `RequestIngress` / `RequestIngressSource` | function / _type_ | a typed key the code that builds a `Request` attaches a value to (`attach(request, value)`) and an endpoint, `authorize`, `beforeHandle` or `onError` reads from its `ctx` (`from(ctx)`); a header, `clone()` and `new Request(request)` carry nothing, a second `attach` is refused, and `ctx.req` is the very request the handler received — [guide](../guide/server.md#request-attributes-from-the-ingress) |
23513
23553
  | `ProxyOriginConfig` | _type_ | explicit real-peer trust for Bun `createServer({ proxyOrigin })`; strict external-scheme normalization before composition — [details](../guide/server.md#external-origin-behind-a-trusted-proxy) |
23514
- | `UnixListenConfig` | _type_ | unix listener — a socket path, or `{ path, mode }` to tighten the file mode after listen |
23554
+ | `UnixListenConfig` | _type_ | unix listener — a socket path bound under the process umask, or `{ path, mode }` for a socket born with exactly `mode` (`bindUnixSocket`) |
23515
23555
  | `BunServerHandle` | _type_ | managed Bun handle (`url`, `port`, `runtime`, `status`, `shutdown`) |
23516
23556
  | `ManagedServerHandle` | _type_ | shared lifecycle shape generic over the runtime escape hatch |
23517
23557
  | `ShutdownOptionsSchema` / `ShutdownOptions` | schema / _type_ | HTTP/application grace, a separate WebSocket close-handshake bound, bounded forced-completion timeout, retry hint and optional external abort signal |
@@ -25173,6 +25213,7 @@ available from `stitchkit/contract`.
25173
25213
  | `sweepAtomicStaging` / `SweepAtomicStagingOptions` | function / _type_ | remove abandoned staging files from one `directory`: only regular files matching `isAtomicStagingName` and older than the required `olderThanMs`, never following a symlink or entering a subdirectory; stops on `signal`; returns the removed names, `[]` for a `directory` that does not exist |
25174
25214
  | `withExclusiveLock` / `ExclusiveLockOptions` / `ExclusiveLock` / `ExclusiveLockOwner` | function / _type_ | run work under an exclusive lock between processes — a file recording its owner (pid, host, machine identity, time and nullable kernel process identity); waits up to `timeoutMs` (default 10 s) and stops on `signal`; a dead owner on this machine is taken over, a live, slow or foreign one never is; a lock recorded by this very process is held only while one of its descriptors is open on it, so the lock an earlier image of the same PID left (`bun --watch` restarts in place) is taken over at once; the lock is published with its owner already recorded (temporary file plus hard link), so a stalled holder is never displaced; a legacy empty lock file is taken by age only when `ownerlessGraceMs` is a number (default `null`: never; an abandoned empty reclaim guard is taken after 5 000 ms unless a value is set); exact `mode` is independent of umask; shared readers need a common group and traversable directories |
25175
25215
  | `ExclusiveLockError` | class | `LOCK_TIMEOUT` naming the resource and its holder, or `LOCK_ABORTED` with the signal's reason |
25216
+ | `bindUnixSocket` / `UnixSocketBinding` | function / _type_ | bind a unix socket that exists only with `mode` (`0o000`–`0o777`), never wider first: the umask is narrowed for the one synchronous `bind(path)` (`Bun.serve({ unix })`, `node:http`/`node:net` `listen(path)`) and restored before any other JavaScript; the path must be free beforehand and a socket with exactly `mode` afterwards, else it refuses (a socket born with other rights is removed) — [guide](../guide/native-io.md#a-unix-socket-private-from-birth) |
25176
25217
  | `createChunkSpool` | function | the server half of a chunked upload: parts on disk under `owner` + client-minted `uploadId`, each with a size+sha256 receipt; idempotent `open` and `put`, the first writer of a part wins across processes, `assemble` in order once every part is in, `sweep` of untouched uploads — [guide](../guide/client.md#chunked-uploads) |
25177
25218
  | `ChunkSpool` / `ChunkSpoolConfig` / `ChunkSpoolKey` / `ChunkSpoolOpen` / `ChunkSpoolPart` / `ChunkSpoolAssembly` | _type_ | the spool, its directory, part size, file limit, meta schema and age; an upload's key; its declaration; one part; the assembled parts with a concatenating `stream()` |
25178
25219
  | `ChunkSpoolErrorCode` | _type_ | the `AppError` codes a spool refuses with, each with its 4xx status: `UPLOAD_INVALID`, `UPLOAD_TOO_LARGE`, `UPLOAD_NOT_FOUND`, `UPLOAD_CONFLICT`, `UPLOAD_CHUNK_OUT_OF_RANGE`, `UPLOAD_CHUNK_SIZE`, `UPLOAD_INCOMPLETE` |
package/llms.txt CHANGED
@@ -26,7 +26,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
26
26
  - **stitchkit/remote**: [llms/remote.txt](llms/remote.txt) 1.0 KB
27
27
  - **stitchkit/contract**: [llms/contract.txt](llms/contract.txt) 34.1 KB
28
28
  - **stitchkit/primitives**: [llms/primitives.txt](llms/primitives.txt) 13.2 KB
29
- - **stitchkit/server**: [llms/server.txt](llms/server.txt) 44.2 KB → [llms/server.2.txt](llms/server.2.txt) 23.1 KB → [llms/server.3.txt](llms/server.3.txt) 47.0 KB → [llms/server.4.txt](llms/server.4.txt) 38.7 KB → [llms/server.5.txt](llms/server.5.txt) 23.7 KB
29
+ - **stitchkit/server**: [llms/server.txt](llms/server.txt) 44.4 KB → [llms/server.2.txt](llms/server.2.txt) 23.1 KB → [llms/server.3.txt](llms/server.3.txt) 47.0 KB → [llms/server.4.txt](llms/server.4.txt) 38.7 KB → [llms/server.5.txt](llms/server.5.txt) 23.8 KB
30
30
  - **stitchkit/observability**: [llms/observability.txt](llms/observability.txt) 46.9 KB
31
31
  - **stitchkit/agent-runtime**: [llms/agent-runtime.txt](llms/agent-runtime.txt) 5.7 KB → [llms/agent-runtime.2.txt](llms/agent-runtime.2.txt) 44.1 KB → [llms/agent-runtime.3.txt](llms/agent-runtime.3.txt) 42.5 KB → [llms/agent-runtime.4.txt](llms/agent-runtime.4.txt) 45.2 KB → [llms/agent-runtime.5.txt](llms/agent-runtime.5.txt) 11.8 KB
32
32
  - **stitchkit/agent-runtime/testing**: [llms/agent-runtime-testing.txt](llms/agent-runtime-testing.txt) 2.6 KB
@@ -44,7 +44,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
44
44
  - **stitchkit/application/schemas**: [llms/application-schemas.txt](llms/application-schemas.txt) 1.8 KB
45
45
  - **stitchkit/testing**: [llms/testing.txt](llms/testing.txt) 33.7 KB
46
46
  - **stitchkit/agent-runtime/sandbox**: [llms/agent-runtime-sandbox.txt](llms/agent-runtime-sandbox.txt) 8.3 KB
47
- - **stitchkit/files**: [llms/files.txt](llms/files.txt) 5.7 KB
47
+ - **stitchkit/files**: [llms/files.txt](llms/files.txt) 6.2 KB
48
48
  - **stitchkit/telegram**: [llms/telegram.txt](llms/telegram.txt) 34.3 KB → [llms/telegram.2.txt](llms/telegram.2.txt) 13.8 KB
49
49
  - **stitchkit/telegram/grammy**: [llms/telegram-grammy.txt](llms/telegram-grammy.txt) 1.2 KB
50
50
  - **stitchkit/telegram/html**: [llms/telegram-html.txt](llms/telegram-html.txt) 2.7 KB
@@ -65,7 +65,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
65
65
  - **stitchkit/node**: [llms/node.txt](llms/node.txt) 3.1 KB
66
66
  - **stitchkit/agent-runtime/react**: [llms/agent-runtime-react.txt](llms/agent-runtime-react.txt) 1.0 KB
67
67
  - **stitchkit/agent-runtime/realtime**: [llms/agent-runtime-realtime.txt](llms/agent-runtime-realtime.txt) 2.6 KB
68
- - **stitchkit/process**: [llms/process.txt](llms/process.txt) 46.8 KB → [llms/process.2.txt](llms/process.2.txt) 9.1 KB
68
+ - **stitchkit/process**: [llms/process.txt](llms/process.txt) 40.7 KB → [llms/process.2.txt](llms/process.2.txt) 17.2 KB
69
69
  - **stitchkit/process/owner-loss**: [llms/process-owner-loss.txt](llms/process-owner-loss.txt) 0.9 KB
70
70
  - **stitchkit/files/packaging**: [llms/files-packaging.txt](llms/files-packaging.txt) 4.3 KB
71
71
  - **stitchkit/http**: [llms/http.txt](llms/http.txt) 0.9 KB
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stitchkit",
3
- "version": "0.123.3",
3
+ "version": "0.123.4",
4
4
  "description": "Contract-first backend framework — one defineContract() into an HTTP API, MCP tools, AI-agent tools and a typed client. Bun and Node.",
5
5
  "keywords": [
6
6
  "bun",