@cortexkit/common-auth 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +4 -4
  2. package/dist/auth-menu/login.d.ts +9 -1
  3. package/dist/auth-menu/login.js +26 -6
  4. package/dist/cachekeep/manager.js +6 -1
  5. package/dist/claustrum/consumer.js +28 -14
  6. package/dist/claustrum/enrollment.d.ts +3 -2
  7. package/dist/claustrum/enrollment.js +84 -42
  8. package/dist/claustrum/roster.js +2 -2
  9. package/dist/dump/index.d.ts +4 -3
  10. package/dist/dump/index.js +39 -12
  11. package/dist/fs/atomic-write.d.ts +5 -0
  12. package/dist/fs/atomic-write.js +21 -0
  13. package/dist/fs/index.d.ts +2 -0
  14. package/dist/fs/index.js +1 -0
  15. package/dist/fs/private-files.d.ts +66 -0
  16. package/dist/fs/private-files.js +302 -0
  17. package/dist/fs/refresh-file-lock.d.ts +1 -1
  18. package/dist/fs/refresh-file-lock.js +254 -37
  19. package/dist/fs/with-lock.d.ts +3 -0
  20. package/dist/fs/with-lock.js +4 -0
  21. package/dist/logger/engine.d.ts +6 -8
  22. package/dist/logger/engine.js +126 -11
  23. package/dist/pi-slot/slot.d.ts +2 -0
  24. package/dist/pi-slot/slot.js +34 -6
  25. package/dist/rpc/port-file.js +30 -8
  26. package/dist/rpc/rpc-client.js +15 -1
  27. package/dist/rpc/rpc-server.js +8 -3
  28. package/dist/sidebar-file/sidebar-file.d.ts +5 -4
  29. package/dist/sidebar-file/sidebar-file.js +17 -8
  30. package/dist/store/mutate.js +2 -2
  31. package/dist/store/pool.d.ts +1 -0
  32. package/dist/store/pool.js +3 -0
  33. package/dist/store/refresh-lock.d.ts +4 -0
  34. package/dist/store/refresh-lock.js +5 -0
  35. package/dist/tui-prefs/tui-preferences.js +6 -4
  36. package/dist/tui-prefs/watcher.d.ts +3 -0
  37. package/dist/tui-prefs/watcher.js +26 -10
  38. package/dist/util/any-signal.d.ts +9 -0
  39. package/dist/util/any-signal.js +42 -0
  40. package/package.json +4 -3
package/README.md CHANGED
@@ -11,16 +11,16 @@ Shared libraries for the CortexKit auth plugins for OpenCode and Pi: openai-auth
11
11
 
12
12
  A passing safety test proves little until it has been seen to fail. [`mutations.toml`](mutations.toml) is the checked-in catalogue: each row deliberately breaks one guard in `src/` (or a CI scan script) and names the Bun test that must fail because of it, so a guard cannot silently stop guarding. A row earns its place by guarding a silent, costly failure: lock exclusion, crash safety, credential loss or leakage, a single-use token used twice, misattributed quota, a wire contract, data loss. Style and cosmetics do not.
13
13
 
14
- The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/0c99c7e16d8ae22b6e114136b6b7b68be6f1394e/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
14
+ The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/9d6b663dac487bb982c7bfd18a96eee2292164ad/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
15
15
 
16
16
  ```sh
17
- cargo install --locked --git https://github.com/cortexkit/commons --rev 0c99c7e16d8ae22b6e114136b6b7b68be6f1394e cortexkit-mutate
18
- ckdev-mutate check
17
+ cargo install --locked --git https://github.com/cortexkit/commons --rev 9d6b663dac487bb982c7bfd18a96eee2292164ad cortexkit-mutate
18
+ ckdev-mutate check --strict
19
19
  ckdev-mutate run --all
20
20
  ckdev-mutate run --diff origin/main
21
21
  ckdev-mutate run --only fs-lock-try-once-refuses-held-lock
22
22
  ```
23
23
 
24
- Every row must report CAUGHT. Replay with the Bun version CI pins (1.3.14): the row `rpc-declared-oversize-413-half-closes` guards the RPC server's workaround for Bun 1.3.14 reusing a connection the server refused with 413. Bun 1.4.2 never reuses it, so that row survives there. Rows are command rows: `{test}` is a Bun `-t` filter, a regular expression over the full test name (describe names and test name joined by spaces), so ids are anchored, escaped, and spell each space `\s`. CI replays the rows a pull request's diff selects, the full catalogue on every push to main, and the full catalogue with `--broad` nightly. Never `git checkout` a file while a replay runs: it removes the mutation and fakes a survivor.
24
+ Every row must report CAUGHT. Replay with the Bun version CI pins (1.3.14): the row `rpc-declared-oversize-413-half-closes` guards the RPC server's workaround for Bun 1.3.14 reusing a connection the server refused with 413. Bun 1.4.2 never reuses it, so that row survives there. Rows are command rows: `{test}` is a Bun `-t` filter, a regular expression over the full test name (describe names and test name joined by spaces), so ids are anchored, escaped, and spell each space `\s`. The shared `scripts/list-bun-tests.mjs` asks Bun's JUnit reporter to list every discovered test as skipped with a never-matching selector, then reconstructs full names from nested describe suites and filters them with the row's JavaScript regular expression. It does not duplicate Bun's test-name formatting or run test bodies. `ckdev-mutate check --strict` verifies each active command row's `expect_red` selects a discovered test. CI replays the rows a pull request's diff selects, the full catalogue on every push to main, and the full catalogue with `--broad` nightly. Never `git checkout` a file while a replay runs: it removes the mutation and fakes a survivor.
25
25
 
26
26
  Licensed under MIT; see [LICENSE](LICENSE).
@@ -35,8 +35,16 @@ type BrowserExec = (file: string, args: string[], options: {
35
35
  stdio: 'ignore';
36
36
  timeout: number;
37
37
  }) => unknown;
38
+ type BrowserSpawn = (file: string, args: string[], options: {
39
+ stdio: 'ignore';
40
+ windowsHide: true;
41
+ }) => {
42
+ pid?: number;
43
+ unref(): void;
44
+ on(event: 'error', listener: () => void): unknown;
45
+ };
38
46
  /** Opens a URL with the platform's opener; false when that fails. */
39
- export declare function openBrowserForMenu(url: string, platform?: NodeJS.Platform, execFileSync?: BrowserExec): boolean;
47
+ export declare function openBrowserForMenu(url: string, platform?: NodeJS.Platform, execFileSync?: BrowserExec, spawn?: BrowserSpawn): boolean;
40
48
  /**
41
49
  * Runs a login for the menu: a browser login first and, when no browser can
42
50
  * be opened, a device-code login instead, so a headless machine can still
@@ -1,12 +1,32 @@
1
- import { execFileSync as defaultExecFileSync } from 'node:child_process';
1
+ import { execFileSync as defaultExecFileSync, spawn as defaultSpawn, } from 'node:child_process';
2
2
  /** Opens a URL with the platform's opener; false when that fails. */
3
- export function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync) {
3
+ export function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
4
4
  try {
5
5
  if (platform === 'win32') {
6
- execFileSync('cmd', ['/c', 'start', '', url], {
7
- stdio: 'ignore',
8
- timeout: 3000,
9
- });
6
+ // Start-Process opens the URL with its associated app. Base64 UTF-16LE
7
+ // keeps cmd from parsing the URL; Microsoft documents both options:
8
+ // https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.5
9
+ // https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-encodedcommand-base64encodedcommand
10
+ // PowerShell is launched without waiting for it: a cold Windows
11
+ // PowerShell start took about 6 s on a Windows Server 2022 runner, and a
12
+ // waiting caller with a short timeout killed it before the browser
13
+ // opened. It is not detached: a detached PowerShell has no console and
14
+ // never ran the command on any Windows runner.
15
+ const command = `Start-Process '${url.replaceAll("'", "''")}'`;
16
+ const child = spawn('powershell.exe', [
17
+ '-NoProfile',
18
+ '-NonInteractive',
19
+ '-WindowStyle',
20
+ 'Hidden',
21
+ '-EncodedCommand',
22
+ Buffer.from(command, 'utf16le').toString('base64'),
23
+ ], { stdio: 'ignore', windowsHide: true });
24
+ // A failed launch reports asynchronously; without a listener it would
25
+ // become an uncaught exception after this function has returned.
26
+ child.on('error', () => { });
27
+ child.unref();
28
+ // Node leaves pid undefined when the process could not be started.
29
+ return child.pid !== undefined;
10
30
  }
11
31
  else {
12
32
  execFileSync(platform === 'darwin' ? 'open' : 'xdg-open', [url], {
@@ -1,3 +1,4 @@
1
+ import { combineAbortSignals } from '../util/any-signal.js';
1
2
  import { isWithinCacheKeepWindow } from './window.js';
2
3
  const DEFAULT_TTL_MS = 5 * 60_000;
3
4
  const DEFAULT_MAX_IDLE_WARM_MS = 60 * 60_000;
@@ -350,10 +351,11 @@ export class CacheKeepManager {
350
351
  return;
351
352
  if (this.retireIfExpired(sessionKey, target))
352
353
  return;
353
- const signal = AbortSignal.any([
354
+ const combined = combineAbortSignals([
354
355
  AbortSignal.timeout(this.warmTimeoutMs),
355
356
  this.abortController.signal,
356
357
  ]);
358
+ const signal = combined.signal;
357
359
  let response;
358
360
  let text = '';
359
361
  try {
@@ -368,6 +370,9 @@ export class CacheKeepManager {
368
370
  });
369
371
  return;
370
372
  }
373
+ finally {
374
+ combined.dispose();
375
+ }
371
376
  if (!this.isCurrent(sessionKey, target))
372
377
  return;
373
378
  if (!response.ok) {
@@ -1,4 +1,5 @@
1
1
  import { createLogger } from '../logger/index.js';
2
+ import { combineAbortSignals } from '../util/any-signal.js';
2
3
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
3
4
  import { ClaustrumConsumerError } from './errors.js';
4
5
  import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
@@ -32,30 +33,33 @@ export class ClaustrumConsumer {
32
33
  return (await this.#options.isCustodyActive?.()) ?? true;
33
34
  }
34
35
  #wait(pending, signal) {
35
- const combined = AbortSignal.any([
36
+ const combined = combineAbortSignals([
36
37
  this.#shutdown.signal,
37
38
  ...(signal ? [signal] : []),
38
39
  ]);
39
40
  return new Promise((resolve, reject) => {
40
- const cleanup = () => combined.removeEventListener('abort', abort);
41
+ const cleanup = () => {
42
+ combined.signal.removeEventListener('abort', abort);
43
+ combined.dispose();
44
+ };
41
45
  const abort = () => {
42
46
  cleanup();
43
- reject(combined.reason);
47
+ reject(combined.signal.reason);
44
48
  };
45
- combined.addEventListener('abort', abort, { once: true });
49
+ combined.signal.addEventListener('abort', abort, { once: true });
46
50
  // Observe the operation even after cancellation: shared metadata work may
47
51
  // finish for other callers, and a late connection must still be closed.
48
52
  pending.then((value) => {
49
53
  cleanup();
50
- if (combined.aborted)
51
- reject(combined.reason);
54
+ if (combined.signal.aborted)
55
+ reject(combined.signal.reason);
52
56
  else
53
57
  resolve(value);
54
58
  }, (error) => {
55
59
  cleanup();
56
60
  reject(error);
57
61
  });
58
- if (combined.aborted)
62
+ if (combined.signal.aborted)
59
63
  abort();
60
64
  });
61
65
  }
@@ -181,13 +185,23 @@ export class ClaustrumConsumer {
181
185
  configured.credentialId !== observed.credentialId ||
182
186
  configured.accountIdentity !== observed.accountIdentity)
183
187
  throw new ClaustrumConsumerError('route-unavailable', 'Claustrum route is disabled, removed or changed');
184
- return (await this.#wait(this.#getCustody(), signal)).authorize({
185
- credentialId: configured.credentialId,
186
- credentialType: configured.credentialType,
187
- ...(configured.accountIdentity !== undefined && {
188
- accountIdentity: configured.accountIdentity,
189
- }),
190
- }, AbortSignal.any([this.#shutdown.signal, ...(signal ? [signal] : [])]));
188
+ const custody = await this.#wait(this.#getCustody(), signal);
189
+ const combined = combineAbortSignals([
190
+ this.#shutdown.signal,
191
+ ...(signal ? [signal] : []),
192
+ ]);
193
+ try {
194
+ return await custody.authorize({
195
+ credentialId: configured.credentialId,
196
+ credentialType: configured.credentialType,
197
+ ...(configured.accountIdentity !== undefined && {
198
+ accountIdentity: configured.accountIdentity,
199
+ }),
200
+ }, combined.signal);
201
+ }
202
+ finally {
203
+ combined.dispose();
204
+ }
191
205
  }
192
206
  async reportFailure(attempt, status, source) {
193
207
  this.#assertOpen();
@@ -97,8 +97,9 @@ export interface EnrollmentAncestorOptions {
97
97
  groupPath?: string;
98
98
  }
99
99
  /**
100
- * Protect setup writes from directory replacement. Group write access is safe
101
- * only when local account records prove that the effective user's group is private.
100
+ * Protect setup writes from directory replacement. On POSIX, group write access
101
+ * is safe only when local records prove the effective user's group is private;
102
+ * sticky ancestors are accepted. Windows uses the shared safe-parent policy.
102
103
  */
103
104
  export declare function refuseWritableAncestor(parent: string, options?: EnrollmentAncestorOptions): Promise<void>;
104
105
  export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentStatus>;
@@ -4,6 +4,7 @@ import { chmod, mkdir, open, readFile, realpath, rename, stat, unlink, } from 'n
4
4
  import { basename, dirname, extname, isAbsolute, join, resolve, } from 'node:path';
5
5
  import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile, } from '@cortexkit/claustrum-client';
6
6
  import { acquireRefreshFileLock } from '../fs/index.js';
7
+ import { ensurePrivateDirectory as ensureWindowsDirectory, PrivateFileError, readPrivateText, verifySafeDirectory, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
7
8
  import { ClaustrumConsumerError } from './errors.js';
8
9
  const ENROLLMENT_SCHEMA = 1;
9
10
  const ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
@@ -198,6 +199,21 @@ function parseSecretJson(text) {
198
199
  }
199
200
  }
200
201
  async function readBoundedJson(path) {
202
+ if (windowsPrivateFiles) {
203
+ try {
204
+ await ensureWindowsDirectory(dirname(path));
205
+ const text = await readPrivateText(path, true);
206
+ if (Buffer.byteLength(text) > ENROLLMENT_FILE_MAX_BYTES) {
207
+ throw new ClaustrumConsumerError('unsafe-file', 'Claustrum enrollment file is too large');
208
+ }
209
+ return parseSecretJson(text);
210
+ }
211
+ catch (error) {
212
+ if (error.code === 'ENOENT')
213
+ return undefined;
214
+ throw error;
215
+ }
216
+ }
201
217
  let descriptor;
202
218
  try {
203
219
  // O_NOFOLLOW: a symlink planted at the path must not redirect a secret read.
@@ -267,52 +283,76 @@ async function isPrivateGroup(uid, gid, options) {
267
283
  return false;
268
284
  }
269
285
  }
286
+ function ancestorPolicyOptions(options) {
287
+ if (!options.passwdPath && !options.groupPath)
288
+ return undefined;
289
+ return {
290
+ fs: {
291
+ readFile: (path) => readFile(path === '/etc/passwd'
292
+ ? (options.passwdPath ?? path)
293
+ : path === '/etc/group'
294
+ ? (options.groupPath ?? path)
295
+ : path),
296
+ },
297
+ };
298
+ }
270
299
  /**
271
- * Protect setup writes from directory replacement. Group write access is safe
272
- * only when local account records prove that the effective user's group is private.
300
+ * Protect setup writes from directory replacement. On POSIX, group write access
301
+ * is safe only when local records prove the effective user's group is private;
302
+ * sticky ancestors are accepted. Windows uses the shared safe-parent policy.
273
303
  */
274
304
  export async function refuseWritableAncestor(parent, options = {}) {
275
- const uid = process.geteuid?.();
276
- if (uid === undefined)
277
- return;
278
- const gid = process.getegid?.();
279
- let component;
280
- try {
281
- component = await realpath(parent);
282
- }
283
- catch {
284
- return;
285
- }
286
- // Load lazily, once per traversal: account changes take effect on the next write.
287
- let privateGroup;
288
- for (;;) {
289
- const metadata = await stat(component).catch(() => undefined);
290
- if (metadata &&
291
- (metadata.mode & 0o022) !== 0 &&
292
- (metadata.mode & 0o1000) === 0) {
293
- if (privateGroup === undefined) {
294
- privateGroup =
295
- gid !== undefined && (await isPrivateGroup(uid, gid, options));
296
- }
297
- if ((metadata.mode & 0o002) !== 0 ||
298
- metadata.uid !== uid ||
299
- metadata.gid !== gid ||
300
- !privateGroup) {
301
- throw new ClaustrumConsumerError('unsafe-file', `Claustrum enrollment path has a writable ancestor: ${component}. Another user could replace it. Run: chmod g-w,o-w ${component}`);
302
- }
305
+ if (!windowsPrivateFiles) {
306
+ const uid = process.geteuid?.();
307
+ if (uid === undefined)
308
+ return;
309
+ const gid = process.getegid?.();
310
+ let component;
311
+ try {
312
+ component = await realpath(parent);
303
313
  }
304
- const next = dirname(component);
305
- if (next === component)
314
+ catch {
306
315
  return;
307
- component = next;
316
+ }
317
+ // Load lazily, once per traversal: account changes take effect on the next write.
318
+ let privateGroup;
319
+ for (;;) {
320
+ const metadata = await stat(component).catch(() => undefined);
321
+ if (metadata &&
322
+ (metadata.mode & 0o022) !== 0 &&
323
+ (metadata.mode & 0o1000) === 0) {
324
+ if (privateGroup === undefined) {
325
+ privateGroup =
326
+ gid !== undefined && (await isPrivateGroup(uid, gid, options));
327
+ }
328
+ if ((metadata.mode & 0o002) !== 0 ||
329
+ metadata.uid !== uid ||
330
+ metadata.gid !== gid ||
331
+ !privateGroup) {
332
+ throw new ClaustrumConsumerError('unsafe-file', `Claustrum enrollment path has a writable ancestor: ${component}. Another user could replace it. Run: chmod g-w,o-w ${component}`);
333
+ }
334
+ }
335
+ const next = dirname(component);
336
+ if (next === component)
337
+ return;
338
+ component = next;
339
+ }
340
+ }
341
+ try {
342
+ await verifySafeDirectory(parent, ancestorPolicyOptions(options));
343
+ }
344
+ catch (error) {
345
+ if (!(error instanceof PrivateFileError))
346
+ throw error;
347
+ throw new ClaustrumConsumerError('unsafe-file', `Claustrum enrollment parent refused: ${error.path} (${error.reason ?? error.code}). Use a folder that other users cannot write or replace.`);
308
348
  }
309
349
  }
310
- /**
311
- * Create the enrollment directory owner-only (0700), and tighten it to 0700
312
- * when it already exists with group or other bits, so the token and the
313
- * request secret never sit in a directory another account can list.
314
- */
315
- async function ensurePrivateDirectory(directory) {
350
+ /** POSIX tightens the enrollment directory to 0700; Windows verifies safe ancestry without modifying existing parents. */
351
+ async function ensurePrivateDirectory(directory, options = {}) {
352
+ if (windowsPrivateFiles) {
353
+ await ensureWindowsDirectory(directory, false, ancestorPolicyOptions(options));
354
+ return;
355
+ }
316
356
  await mkdir(directory, { recursive: true, mode: 0o700 });
317
357
  const metadata = await stat(directory);
318
358
  const uid = process.geteuid?.();
@@ -324,12 +364,14 @@ async function ensurePrivateDirectory(directory) {
324
364
  }
325
365
  async function writeStateAtomic(path, state, ancestorOptions = {}) {
326
366
  const parent = dirname(path);
327
- await ensurePrivateDirectory(parent);
367
+ await ensurePrivateDirectory(parent, ancestorOptions);
328
368
  await refuseWritableAncestor(parent, ancestorOptions);
329
369
  const bytes = `${JSON.stringify(state)}\n`;
330
370
  if (Buffer.byteLength(bytes) > ENROLLMENT_FILE_MAX_BYTES) {
331
371
  throw new ClaustrumConsumerError('invalid-state', 'Claustrum enrollment state is too large');
332
372
  }
373
+ if (windowsPrivateFiles)
374
+ return writePrivateAtomic(path, bytes);
333
375
  const temporary = join(parent, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
334
376
  let descriptor;
335
377
  let created = false;
@@ -496,7 +538,7 @@ export class ClaustrumEnrollmentManager {
496
538
  return statusFromState(blocked);
497
539
  }
498
540
  async reconcile() {
499
- await ensurePrivateDirectory(dirname(this.#paths.statePath));
541
+ await ensurePrivateDirectory(dirname(this.#paths.statePath), this.#ancestorOptions);
500
542
  const lock = await acquireRefreshFileLock({
501
543
  name: 'ceremony',
502
544
  path: this.#paths.statePath,
@@ -616,7 +658,7 @@ export class ClaustrumEnrollmentManager {
616
658
  }
617
659
  // The vault returns the token exactly once: it reaches disk before the
618
660
  // pending metadata (and its secret) is replaced.
619
- await ensurePrivateDirectory(dirname(this.#paths.tokenPath));
661
+ await ensurePrivateDirectory(dirname(this.#paths.tokenPath), this.#ancestorOptions);
620
662
  await refuseWritableAncestor(dirname(this.#paths.tokenPath), this.#ancestorOptions);
621
663
  await this.#writeTokenFile(this.#paths.tokenPath, {
622
664
  token: outcome.token,
@@ -1,6 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { readFile } from 'node:fs/promises';
3
2
  import { acquireRefreshFileLock, withLock, writeJsonAtomic, } from '../fs/index.js';
3
+ import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
4
4
  import { isQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
@@ -289,7 +289,7 @@ function decodeRoster(value) {
289
289
  export async function readVaultRoster(path) {
290
290
  let text;
291
291
  try {
292
- text = await readFile(path, 'utf8');
292
+ text = await readPrivateText(path, windowsPrivateFiles);
293
293
  }
294
294
  catch (error) {
295
295
  if (error.code === 'ENOENT')
@@ -171,10 +171,11 @@ export interface SweepDumpDirectoryOptions {
171
171
  * writes are counted or removed, so unrelated files in a directory the user
172
172
  * chose survive. A dump's files are evicted together, oldest dump first by
173
173
  * its newest file, because a body without its metadata (or the reverse) is no
174
- * use to anyone. Dumps younger than `minAgeMs`, protected paths and symlinks
175
- * are kept, and a symlinked directory is refused outright. Response staging
174
+ * use to anyone. Dumps younger than `minAgeMs`, caller-listed `protectedPaths`
175
+ * (such as a just-written dump) and symlinks are kept, and a symlinked directory
176
+ * is refused outright. Response staging
176
177
  * files left by a crash are reclaimed once stale, even under the cap.
177
- * Best-effort: a failure removes less, and never throws.
178
+ * Cleanup is best-effort, but Windows refuses an unverified private directory.
178
179
  */
179
180
  export declare function sweepDumpDirectory(options: SweepDumpDirectoryOptions): Promise<DumpSweepResult>;
180
181
  /**
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { chmod, lstat, mkdir, open, readdir, readFile, rename, unlink, writeFile, } from 'node:fs/promises';
2
+ import { chmod, lstat, mkdir, open, readdir, rename, unlink, writeFile, } from 'node:fs/promises';
3
3
  import { join, resolve } from 'node:path';
4
+ import { createPrivateBytes, ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
4
5
  import { createRedactor } from '../logger/redact.js';
5
6
  const PREVIOUS_BODY_LIMIT = 100;
6
7
  const UNKNOWN_SESSION = 'session-unknown';
@@ -36,10 +37,11 @@ function isPartialName(name) {
36
37
  * writes are counted or removed, so unrelated files in a directory the user
37
38
  * chose survive. A dump's files are evicted together, oldest dump first by
38
39
  * its newest file, because a body without its metadata (or the reverse) is no
39
- * use to anyone. Dumps younger than `minAgeMs`, protected paths and symlinks
40
- * are kept, and a symlinked directory is refused outright. Response staging
40
+ * use to anyone. Dumps younger than `minAgeMs`, caller-listed `protectedPaths`
41
+ * (such as a just-written dump) and symlinks are kept, and a symlinked directory
42
+ * is refused outright. Response staging
41
43
  * files left by a crash are reclaimed once stale, even under the cap.
42
- * Best-effort: a failure removes less, and never throws.
44
+ * Cleanup is best-effort, but Windows refuses an unverified private directory.
43
45
  */
44
46
  export async function sweepDumpDirectory(options) {
45
47
  const { dir, maxBytes } = options;
@@ -50,6 +52,8 @@ export async function sweepDumpDirectory(options) {
50
52
  if (!(maxBytes > 0))
51
53
  return empty;
52
54
  try {
55
+ if (windowsPrivateFiles)
56
+ await verifyPrivate(dir, 'directory');
53
57
  if ((await lstat(dir)).isSymbolicLink())
54
58
  return empty;
55
59
  const protectedPaths = new Set((options.protectedPaths ?? []).map((path) => resolve(path)));
@@ -123,7 +127,10 @@ export async function sweepDumpDirectory(options) {
123
127
  }
124
128
  return { removed, freedBytes };
125
129
  }
126
- catch {
130
+ catch (error) {
131
+ if (error instanceof PrivateFileError &&
132
+ error.code === 'ERR_PRIVATE_FILES_SECURITY')
133
+ throw error;
127
134
  return empty;
128
135
  }
129
136
  }
@@ -133,6 +140,11 @@ export async function sweepDumpDirectory(options) {
133
140
  * staging name is never followed.
134
141
  */
135
142
  async function replaceFile(path, text, stageName) {
143
+ if (windowsPrivateFiles) {
144
+ return writePrivateAtomic(path, text, {
145
+ stagePath: `${path}.${stageName ? stageName() : randomBytes(12).toString('hex')}.partial`,
146
+ });
147
+ }
136
148
  for (let attempt = 0;; attempt += 1) {
137
149
  const staging = `${path}.${stageName ? stageName() : randomBytes(12).toString('hex')}.partial`;
138
150
  let created = false;
@@ -322,12 +334,15 @@ export function createDumper(options) {
322
334
  .reverse();
323
335
  for (const name of candidates) {
324
336
  try {
325
- const metadata = JSON.parse(await readFile(join(dir, name), 'utf8'));
337
+ const metadata = JSON.parse(await readPrivateText(join(dir, name), windowsPrivateFiles));
326
338
  if (metadata?.baselineKey !== baselineKey)
327
339
  continue;
328
- return await readFile(join(dir, name.replace(/\.meta\.json$/, '.body.json')), 'utf8');
340
+ return await readPrivateText(join(dir, name.replace(/\.meta\.json$/, '.body.json')), windowsPrivateFiles);
329
341
  }
330
- catch {
342
+ catch (error) {
343
+ if (error instanceof PrivateFileError &&
344
+ (windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
345
+ throw error;
331
346
  // A file removed or half-written by another process: try the next.
332
347
  }
333
348
  }
@@ -372,9 +387,13 @@ export function createDumper(options) {
372
387
  // full session id.
373
388
  const baselineKey = hashText(`${input.channel}\u0000${session}`);
374
389
  try {
375
- await mkdir(dir, { recursive: true, mode: 0o700 });
376
- // mkdir's mode does not apply to a directory that already exists.
377
- await chmod(dir, 0o700);
390
+ if (windowsPrivateFiles)
391
+ await ensurePrivateDirectory(dir);
392
+ else {
393
+ await mkdir(dir, { recursive: true, mode: 0o700 });
394
+ // mkdir's mode does not apply to a directory that already exists.
395
+ await chmod(dir, 0o700);
396
+ }
378
397
  let previous = previousBodies.get(baselineKey);
379
398
  let baselineSource = previous === undefined ? undefined : 'memory';
380
399
  if (previous === undefined) {
@@ -418,7 +437,9 @@ export function createDumper(options) {
418
437
  : Object.fromEntries(new Headers(input.headers).entries()),
419
438
  });
420
439
  // `wx`: a name collision fails loudly instead of overwriting a dump.
421
- const write = (path, text) => writeFile(path, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
440
+ const write = (path, text) => windowsPrivateFiles
441
+ ? createPrivateBytes(path, text)
442
+ : writeFile(path, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
422
443
  const writes = [
423
444
  [files.body, body.text],
424
445
  [files.metadata, `${JSON.stringify(metadata, null, 2)}\n`],
@@ -443,6 +464,9 @@ export function createDumper(options) {
443
464
  return { id, files, responseFile: `${prefix}.response.json` };
444
465
  }
445
466
  catch (error) {
467
+ if (error instanceof PrivateFileError &&
468
+ (windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
469
+ throw error;
446
470
  log?.warn('request dump failed', {
447
471
  session: shortSession(session),
448
472
  error: error instanceof Error ? error.message : String(error),
@@ -506,6 +530,9 @@ export function createDumper(options) {
506
530
  return result.responseFile;
507
531
  }
508
532
  catch (error) {
533
+ if (error instanceof PrivateFileError &&
534
+ (windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
535
+ throw error;
509
536
  log?.warn('response dump failed', {
510
537
  id: result.id,
511
538
  error: error instanceof Error ? error.message : String(error),
@@ -1,3 +1,4 @@
1
+ import { type PrivateWriteOutcome } from './private-files.js';
1
2
  export interface AtomicWriteOptions {
2
3
  serialize?: (value: unknown) => string;
3
4
  beforeRename?: () => Promise<void>;
@@ -5,6 +6,10 @@ export interface AtomicWriteOptions {
5
6
  stageName?: () => string;
6
7
  /** Sync the staged file and, after rename, its parent directory. Opt-in. */
7
8
  durable?: boolean;
9
+ /** Windows opt-in: flush file bytes, without promising directory metadata durability. */
10
+ durability?: 'file-only-on-windows';
11
+ /** Reports Windows rename success, file/directory durability, retry counts and error codes, never file bytes. */
12
+ onOutcome?: (outcome: PrivateWriteOutcome) => void;
8
13
  }
9
14
  /** Internal classification of fsync failures, including a failure after rename. */
10
15
  export declare class AtomicSyncError extends Error {
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { mkdir, open, rename, rm } from 'node:fs/promises';
3
3
  import { dirname } from 'node:path';
4
+ import { PrivateFileError, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
4
5
  /** Internal classification of fsync failures, including a failure after rename. */
5
6
  export class AtomicSyncError extends Error {
6
7
  constructor(cause) {
@@ -16,6 +17,18 @@ export async function writeJsonAtomic(path, value, options = {}) {
16
17
  * and removed ids here, because a later directory sync cannot undo the rename.
17
18
  */
18
19
  export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
20
+ if (windowsPrivateFiles) {
21
+ return writePrivateAtomic(path, options.serialize
22
+ ? options.serialize(value)
23
+ : `${JSON.stringify(value, null, 2)}\n`, {
24
+ beforeRename: options.beforeRename,
25
+ stagePath: `${path}.${(options.stageName ?? randomUUID)()}.tmp`,
26
+ onRenamed,
27
+ durable: options.durable,
28
+ durability: options.durability,
29
+ onOutcome: options.onOutcome,
30
+ });
31
+ }
19
32
  await mkdir(dirname(path), { recursive: true });
20
33
  const tempPath = `${path}.${(options.stageName ?? randomUUID)()}.tmp`;
21
34
  let handle;
@@ -63,6 +76,14 @@ export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
63
76
  }
64
77
  /** Make an already renamed file and its directory durable without rewriting bytes. */
65
78
  export async function syncJsonFile(path) {
79
+ if (windowsPrivateFiles) {
80
+ await verifyPrivate(path, 'file');
81
+ const error = new PrivateFileError(path, 'directory-sync-unsupported', {
82
+ code: 'ENOTSUP',
83
+ });
84
+ error.published = true;
85
+ throw error;
86
+ }
66
87
  const file = await open(path, 'r');
67
88
  try {
68
89
  await file.sync();
@@ -1,6 +1,8 @@
1
1
  export type { AtomicWriteOptions } from './atomic-write.js';
2
2
  export { writeJsonAtomic } from './atomic-write.js';
3
3
  export { WRITER_LOCK_CONSTANTS } from './lock-constants.js';
4
+ export type { PrivateWriteOutcome } from './private-files.js';
5
+ export { PrivateFileError } from './private-files.js';
4
6
  export type { LockLoss, RefreshFileLock } from './refresh-file-lock.js';
5
7
  export { acquireRefreshFileLock, isLostMarkerRaceError, } from './refresh-file-lock.js';
6
8
  export type { LockOptions, LockOwnershipDetails } from './with-lock.js';
package/dist/fs/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { writeJsonAtomic } from './atomic-write.js';
2
2
  export { WRITER_LOCK_CONSTANTS } from './lock-constants.js';
3
+ export { PrivateFileError } from './private-files.js';
3
4
  // The try-once lock underneath withLock, for callers that hold a lock across
4
5
  // several steps or poll instead of waiting (for example a refresh lease).
5
6
  export { acquireRefreshFileLock, isLostMarkerRaceError, } from './refresh-file-lock.js';