@cortexkit/common-auth 0.49.1 → 0.50.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.
@@ -0,0 +1,17 @@
1
+ import type * as syncFs from 'node:fs';
2
+ import type * as fs from 'node:fs/promises';
3
+ type FilePathFs = Pick<typeof fs, 'lstat' | 'readlink' | 'realpath'>;
4
+ type FilePathSyncFs = Pick<typeof syncFs, 'lstatSync' | 'readlinkSync' | 'realpathSync'>;
5
+ /**
6
+ * Canonical path of a file that other processes may replace by write-and-rename.
7
+ *
8
+ * On Linux, Bun's realpath on such a file can answer "<file> (deleted)" (Bun
9
+ * 1.3) or ENOENT (Bun 1.4) during the rename. So this resolves the folder with
10
+ * realpath and appends the name, then follows a file symlink one readlink hop at
11
+ * a time, at most 40 hops. A missing file resolves to its would-be path; a
12
+ * dangling link or a loop throws. Pass `node:fs/promises` (or a test double).
13
+ */
14
+ export declare function canonicalFilePath(file: string, fs: FilePathFs): Promise<string>;
15
+ /** Synchronous counterpart of canonicalFilePath; pass `node:fs`. */
16
+ export declare function canonicalFilePathSync(file: string, fs: FilePathSyncFs): string;
17
+ export {};
@@ -0,0 +1,57 @@
1
+ import { basename, dirname, join, resolve } from 'node:path';
2
+ const maxSymlinkHops = 40;
3
+ // Same shape as Node's realpath ELOOP, so callers that branch on `code` keep working.
4
+ function symlinkLoop(file) {
5
+ return Object.assign(new Error(`ELOOP: too many symbolic links encountered, realpath '${file}'`), { code: 'ELOOP', syscall: 'realpath', path: file });
6
+ }
7
+ /**
8
+ * Canonical path of a file that other processes may replace by write-and-rename.
9
+ *
10
+ * On Linux, Bun's realpath on such a file can answer "<file> (deleted)" (Bun
11
+ * 1.3) or ENOENT (Bun 1.4) during the rename. So this resolves the folder with
12
+ * realpath and appends the name, then follows a file symlink one readlink hop at
13
+ * a time, at most 40 hops. A missing file resolves to its would-be path; a
14
+ * dangling link or a loop throws. Pass `node:fs/promises` (or a test double).
15
+ */
16
+ export async function canonicalFilePath(file, fs) {
17
+ let target = file;
18
+ for (let hops = 0;; hops++) {
19
+ // Bun can report an unlinked inode's " (deleted)" name for realpath(file).
20
+ target = join(await fs.realpath(dirname(target)), basename(target));
21
+ let isSymlink;
22
+ try {
23
+ isSymlink = (await fs.lstat(target)).isSymbolicLink();
24
+ }
25
+ catch (error) {
26
+ if (error.code === 'ENOENT' && hops === 0)
27
+ return target;
28
+ throw error;
29
+ }
30
+ if (!isSymlink)
31
+ return target;
32
+ if (hops >= maxSymlinkHops)
33
+ throw symlinkLoop(file);
34
+ target = resolve(dirname(target), await fs.readlink(target));
35
+ }
36
+ }
37
+ /** Synchronous counterpart of canonicalFilePath; pass `node:fs`. */
38
+ export function canonicalFilePathSync(file, fs) {
39
+ let target = file;
40
+ for (let hops = 0;; hops++) {
41
+ target = join(fs.realpathSync(dirname(target)), basename(target));
42
+ let isSymlink;
43
+ try {
44
+ isSymlink = fs.lstatSync(target).isSymbolicLink();
45
+ }
46
+ catch (error) {
47
+ if (error.code === 'ENOENT' && hops === 0)
48
+ return target;
49
+ throw error;
50
+ }
51
+ if (!isSymlink)
52
+ return target;
53
+ if (hops >= maxSymlinkHops)
54
+ throw symlinkLoop(file);
55
+ target = resolve(dirname(target), fs.readlinkSync(target));
56
+ }
57
+ }
@@ -1,5 +1,6 @@
1
1
  export type { AtomicWriteOptions } from './atomic-write.js';
2
2
  export { writeJsonAtomic } from './atomic-write.js';
3
+ export { canonicalFilePath, canonicalFilePathSync, } from './canonical-file-path.js';
3
4
  export { WRITER_LOCK_CONSTANTS } from './lock-constants.js';
4
5
  export type { PrivateWriteOutcome } from './private-files.js';
5
6
  export { PrivateFileError } from './private-files.js';
package/dist/fs/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  export { writeJsonAtomic } from './atomic-write.js';
2
+ // Canonical path of a file other processes may atomically replace: resolves
3
+ // the folder, never the file itself (see canonical-file-path.ts).
4
+ export { canonicalFilePath, canonicalFilePathSync, } from './canonical-file-path.js';
2
5
  export { WRITER_LOCK_CONSTANTS } from './lock-constants.js';
3
6
  export { PrivateFileError } from './private-files.js';
4
7
  // The try-once lock underneath withLock, for callers that hold a lock across
@@ -92,7 +92,7 @@ export const confirmedAffinity = immutable({
92
92
  export const earliestPoolEngine = immutable({
93
93
  evidence: 'typed',
94
94
  markers: hosts(ANTIGRAVITY_FAILURE_LADDER),
95
- readingClearsCoveredScopes: 'off',
95
+ readingClearsCoveredScopes: 'on',
96
96
  successClearsCoveredScopes: 'off',
97
97
  unknown: hosts(reselect),
98
98
  shortLimit: {
@@ -1,5 +1,5 @@
1
1
  import * as fs from 'node:fs/promises';
2
- type SettingsFs = Pick<typeof fs, 'readFile' | 'stat' | 'lstat' | 'realpath' | 'open' | 'rename' | 'link' | 'unlink' | 'mkdir' | 'readdir'>;
2
+ type SettingsFs = Pick<typeof fs, 'readFile' | 'stat' | 'lstat' | 'readlink' | 'realpath' | 'open' | 'rename' | 'link' | 'unlink' | 'mkdir' | 'readdir'>;
3
3
  export declare const SettingsFs: SettingsFs;
4
4
  /** Internal test hook; omitted methods always use the native implementation. */
5
5
  export declare function setSettingsFsForTest(overrides?: Partial<SettingsFs>): void;
@@ -3,6 +3,7 @@ const defaults = {
3
3
  readFile: fs.readFile,
4
4
  stat: fs.stat,
5
5
  lstat: fs.lstat,
6
+ readlink: fs.readlink,
6
7
  realpath: fs.realpath,
7
8
  open: fs.open,
8
9
  rename: fs.rename,
@@ -1,4 +1,5 @@
1
- import { basename, dirname, join } from 'node:path';
1
+ import { dirname } from 'node:path';
2
+ import { canonicalFilePath } from '../fs/canonical-file-path.js';
2
3
  import { ensurePrivateDirectory } from '../fs/private-files.js';
3
4
  import { withLock } from '../fs/with-lock.js';
4
5
  import { deepFreeze } from './descriptors.js';
@@ -19,29 +20,10 @@ function unavailable(file, cause) {
19
20
  }
20
21
  async function writeTarget(file) {
21
22
  try {
22
- return await SettingsFs.realpath(file);
23
+ return await canonicalFilePath(file, SettingsFs);
23
24
  }
24
25
  catch (error) {
25
- if (error.code !== 'ENOENT')
26
- unavailable(file, error);
27
- let isSymlink = false;
28
- try {
29
- isSymlink = (await SettingsFs.lstat(file)).isSymbolicLink();
30
- }
31
- catch (lstatError) {
32
- if (lstatError.code !== 'ENOENT')
33
- unavailable(file, lstatError);
34
- }
35
- // Only a symlink whose realpath is missing is a dangling entry.
36
- if (isSymlink)
37
- unavailable(file, error);
38
- // Bun 1.4 can fail realpath for regular files during a concurrent atomic replace.
39
- try {
40
- return join(await SettingsFs.realpath(dirname(file)), basename(file));
41
- }
42
- catch (parentError) {
43
- unavailable(file, parentError);
44
- }
26
+ unavailable(file, error);
45
27
  }
46
28
  }
47
29
  /** Lock the canonical user file so symlink aliases serialize the same edits. */
@@ -19,4 +19,4 @@ export type { PullReason } from './runtime.js';
19
19
  export type { ApiKeyCredential, CredentialStampStatus, OAuthCredential, PoolCredential, PoolRow, ProviderStateCodec, ProviderStateDrop, ProviderStateReplacement, QuotaCodec, RotateCredential, StoredCredential, } from './schema.js';
20
20
  export { fingerprintOf, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, PROVIDER_STATE_KEY, REFRESH_STAMP_TOLERANCE_MS, rowLockKey, } from './schema.js';
21
21
  export type { PoolSettings, SettingsMutator, SettingsRead, UpdateSettingsOptions, UpdateSettingsResult, } from './settings.js';
22
- export { POOL_OWNED_KEYS } from './settings.js';
22
+ export { POOL_OWNED_KEYS, readPoolSettingsAt } from './settings.js';
@@ -4,4 +4,4 @@ export { openPoolStore } from './pool.js';
4
4
  export { DECLINE_TRANSITION } from './provider-state.js';
5
5
  export { POOL_LOCK_DEFAULTS } from './refresh-lock.js';
6
6
  export { fingerprintOf, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, PROVIDER_STATE_KEY, REFRESH_STAMP_TOLERANCE_MS, rowLockKey, } from './schema.js';
7
- export { POOL_OWNED_KEYS } from './settings.js';
7
+ export { POOL_OWNED_KEYS, readPoolSettingsAt } from './settings.js';
@@ -52,6 +52,14 @@ export type UpdateSettingsResult = {
52
52
  };
53
53
  /** Reads only the config's settings, without taking a lock or writing anything. */
54
54
  export declare function readPoolSettings(rt: StoreRuntime): Promise<SettingsRead>;
55
+ /**
56
+ * Reads the settings of the pool config at `configPath`, exactly as a store's
57
+ * `readSettings()` does, without opening a store. It reads only that file: no
58
+ * state file, lock, write or migration. A plugin that has already resolved
59
+ * which config file to trust (for example, after a location check) reads it
60
+ * here rather than opening a second store on it.
61
+ */
62
+ export declare function readPoolSettingsAt(configPath: string): Promise<SettingsRead>;
55
63
  /**
56
64
  * One locked read-modify-write of the plugin's settings in the config file
57
65
  * the pool lives in. The pool must be ready (a pending migration or a load
@@ -63,9 +63,19 @@ function settingsRefusal(message) {
63
63
  }
64
64
  const settingsCache = new FileReadCache();
65
65
  /** Reads only the config's settings, without taking a lock or writing anything. */
66
- export async function readPoolSettings(rt) {
67
- const read = async ([configPath = rt.ctx.configPath,] = []) => {
68
- const result = await readPoolConfig(configPath);
66
+ export function readPoolSettings(rt) {
67
+ return readPoolSettingsAt(rt.ctx.configPath);
68
+ }
69
+ /**
70
+ * Reads the settings of the pool config at `configPath`, exactly as a store's
71
+ * `readSettings()` does, without opening a store. It reads only that file: no
72
+ * state file, lock, write or migration. A plugin that has already resolved
73
+ * which config file to trust (for example, after a location check) reads it
74
+ * here rather than opening a second store on it.
75
+ */
76
+ export async function readPoolSettingsAt(configPath) {
77
+ const read = async ([path = configPath,] = []) => {
78
+ const result = await readPoolConfig(path);
69
79
  if (result.status === 'error')
70
80
  return { status: 'error', file: 'config', reason: result.reason };
71
81
  return { status: result.status, settings: settingsOf(result.config) };
@@ -73,7 +83,7 @@ export async function readPoolSettings(rt) {
73
83
  // Native Windows security checks cannot be replaced by a stat fingerprint.
74
84
  const result = windowsPrivateFiles
75
85
  ? await read()
76
- : await settingsCache.read([rt.ctx.configPath], read);
86
+ : await settingsCache.read([configPath], read);
77
87
  return structuredClone(result);
78
88
  }
79
89
  /**
@@ -1,4 +1,4 @@
1
- import { type Stats, watch } from 'node:fs';
1
+ import { lstatSync, readlinkSync, realpathSync, type Stats, watch } from 'node:fs';
2
2
  import { PrivateFileError } from '../fs/private-files.js';
3
3
  type Metadata = Pick<Stats, 'mtimeMs' | 'size' | 'ino' | 'dev'> & Partial<Pick<Stats, 'ctimeMs'>>;
4
4
  export interface TuiPreferencesWatchOptions {
@@ -13,6 +13,13 @@ export interface TuiPreferencesWatchOptions {
13
13
  stat?: (file: string) => Promise<Metadata>;
14
14
  };
15
15
  }
16
+ declare const pathFs: {
17
+ lstatSync: typeof lstatSync;
18
+ readlinkSync: typeof readlinkSync;
19
+ realpathSync: typeof realpathSync;
20
+ };
21
+ /** Internal test hook; omitted path operations use the native implementation. */
22
+ export declare function setTuiPreferencesPathFsForTest(overrides?: Partial<typeof pathFs>): void;
16
23
  /**
17
24
  * Share one directory watcher and metadata poll per canonical path, including
18
25
  * across bundled copies. Native events use a 150 ms debounce; missed events
@@ -1,8 +1,15 @@
1
- import { readFileSync, realpathSync, statSync, watch, } from 'node:fs';
1
+ import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync, watch, } from 'node:fs';
2
2
  import { readFile, stat } from 'node:fs/promises';
3
3
  import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { clearTimeout, setTimeout } from 'node:timers';
5
+ import { canonicalFilePathSync } from '../fs/canonical-file-path.js';
5
6
  import { PrivateFileError, readPrivateText, windowsPrivateFiles, } from '../fs/private-files.js';
7
+ const pathFsDefaults = { lstatSync, readlinkSync, realpathSync };
8
+ const pathFs = { ...pathFsDefaults };
9
+ /** Internal test hook; omitted path operations use the native implementation. */
10
+ export function setTuiPreferencesPathFsForTest(overrides) {
11
+ Object.assign(pathFs, pathFsDefaults, overrides);
12
+ }
6
13
  function canonicalPath(file) {
7
14
  const path = resolve(file);
8
15
  // Leave reparse points in the path for private-files' ancestor walk to reject;
@@ -10,7 +17,7 @@ function canonicalPath(file) {
10
17
  if (windowsPrivateFiles)
11
18
  return path;
12
19
  try {
13
- return realpathSync(path);
20
+ return canonicalFilePathSync(path, pathFs);
14
21
  }
15
22
  catch {
16
23
  // Resolve existing ancestors even when the preferences file is not yet present.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.49.1",
3
+ "version": "0.50.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {