@cortexkit/common-auth 0.17.2 → 0.18.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.
@@ -13,7 +13,7 @@ export interface RefreshFileLock {
13
13
  whenLost(): Promise<LockLoss>;
14
14
  hasLost(): boolean;
15
15
  }
16
- export declare function acquireRefreshFileLock(options: {
16
+ type RefreshFileLockOptions = {
17
17
  name: string;
18
18
  ttlMs: number;
19
19
  /**
@@ -22,7 +22,6 @@ export declare function acquireRefreshFileLock(options: {
22
22
  * be one host's path.
23
23
  */
24
24
  path: string;
25
- now?: () => number;
26
25
  renew?: boolean;
27
26
  renewIntervalMs?: number;
28
27
  /** Notifies a live-owner refusal without awaiting; observer failures are ignored. */
@@ -30,4 +29,11 @@ export declare function acquireRefreshFileLock(options: {
30
29
  /** Synchronous, never awaited; throws and returned promise/thenable rejections are isolated. */
31
30
  onRenewalTimer?: (event: 'scheduled' | 'cancelled') => void;
32
31
  onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
32
+ };
33
+ /** Filesystem leases share wall time across all callers and processes. */
34
+ export declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
35
+ /** @internal Clock seam for lease tests; not exported by the package's fs entry point. */
36
+ export declare function acquireRefreshFileLockWithClock(options: RefreshFileLockOptions & {
37
+ now?: () => number;
33
38
  }): Promise<RefreshFileLock | null>;
39
+ export {};
@@ -31,7 +31,12 @@ export function isLostMarkerRaceError(error) {
31
31
  return (code === 'ENOENT' ||
32
32
  (!windowsPrivateFiles && (code === 'EINVAL' || code === 'ENOTDIR')));
33
33
  }
34
- export async function acquireRefreshFileLock(options) {
34
+ /** Filesystem leases share wall time across all callers and processes. */
35
+ export function acquireRefreshFileLock(options) {
36
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
37
+ }
38
+ /** @internal Clock seam for lease tests; not exported by the package's fs entry point. */
39
+ export async function acquireRefreshFileLockWithClock(options) {
35
40
  const lockPath = lockPathFor(options.path, options.name);
36
41
  const legacyOwnerPath = join(lockPath, 'owner.json');
37
42
  const ownerId = randomUUID();
@@ -1,4 +1,4 @@
1
- import { rmdirSync, statSync } from 'node:fs';
1
+ import { rmdirSync, statSync, utimesSync } from 'node:fs';
2
2
  import { mkdir, rmdir, stat, utimes } from 'node:fs/promises';
3
3
  // Protocol source: proper-lockfile 4.1.2 lib/lockfile.js and lib/mtime-precision.js;
4
4
  // line-level citations and the Pi lock options are recorded in docs/sources.md.
@@ -135,7 +135,9 @@ export async function acquirePiLock(authPath, onCompromised, onRenew) {
135
135
  return;
136
136
  let observed;
137
137
  try {
138
- observed = await stat(path);
138
+ // Durable writes can occupy every async filesystem worker in fsync.
139
+ // Renew on the calling thread so their queue cannot consume the lease.
140
+ observed = statSync(path);
139
141
  }
140
142
  catch (error) {
141
143
  retry(error);
@@ -151,12 +153,14 @@ export async function acquirePiLock(authPath, onCompromised, onRenew) {
151
153
  }
152
154
  const next = new Date(precision === 's' ? Math.ceil(Date.now() / 1_000) * 1_000 : Date.now());
153
155
  try {
154
- await utimes(path, next, next);
156
+ utimesSync(path, next, next);
155
157
  }
156
158
  catch (error) {
157
159
  retry(error);
158
160
  return;
159
161
  }
162
+ // A metadata syscall can itself stall; never confirm an expired lease.
163
+ assertFresh();
160
164
  if (released)
161
165
  return;
162
166
  mtime = next.getTime();
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Keeps the Pi install refusal message stable while exposing safe process details.
3
+ * A clipped tail can start inside a credential, so discard its first line—or
4
+ * the whole tail if it has no newline—before redacting.
5
+ */
6
+ export declare class SetupCommandError extends Error {
7
+ readonly step = "pi-install";
8
+ readonly exitCode: number | null;
9
+ readonly signal: string | null;
10
+ readonly stderrTail: string;
11
+ constructor(details: {
12
+ exitCode: number | null;
13
+ signal: string | null;
14
+ stderrTail: string;
15
+ stderrTruncated?: boolean;
16
+ });
17
+ }
@@ -0,0 +1,42 @@
1
+ import { redact } from '../logger/redact.js';
2
+ import { STDERR_TAIL_MAX_BYTES } from './command-runner.js';
3
+ const PI_INSTALL_ERROR_MESSAGE = 'Pi install failed; run pi install after checking your npm connection.';
4
+ function utf8Tail(value) {
5
+ const bytes = Buffer.from(value, 'utf8');
6
+ if (bytes.length <= STDERR_TAIL_MAX_BYTES)
7
+ return value;
8
+ let start = bytes.length - STDERR_TAIL_MAX_BYTES;
9
+ while (start < bytes.length) {
10
+ const byte = bytes[start];
11
+ if (byte === undefined || (byte & 0xc0) !== 0x80)
12
+ break;
13
+ start++;
14
+ }
15
+ return bytes.subarray(start).toString('utf8');
16
+ }
17
+ function dropPartialLine(tail) {
18
+ const newline = tail.indexOf('\n');
19
+ return newline < 0 ? '' : tail.slice(newline + 1);
20
+ }
21
+ /**
22
+ * Keeps the Pi install refusal message stable while exposing safe process details.
23
+ * A clipped tail can start inside a credential, so discard its first line—or
24
+ * the whole tail if it has no newline—before redacting.
25
+ */
26
+ export class SetupCommandError extends Error {
27
+ step = 'pi-install';
28
+ exitCode;
29
+ signal;
30
+ stderrTail;
31
+ constructor(details) {
32
+ super(PI_INSTALL_ERROR_MESSAGE);
33
+ this.name = 'SetupCommandError';
34
+ this.exitCode = details.exitCode;
35
+ this.signal = details.signal;
36
+ const tail = details.stderrTruncated
37
+ ? dropPartialLine(details.stderrTail)
38
+ : details.stderrTail;
39
+ const redacted = redact(tail);
40
+ this.stderrTail = utf8Tail(typeof redacted === 'string' ? redacted : '');
41
+ }
42
+ }
@@ -1,4 +1,5 @@
1
1
  import type { CommandResult, CommandRunner, SetupEnvironment } from './types.js';
2
+ export declare const STDERR_TAIL_MAX_BYTES: number;
2
3
  export declare const defaultCommandRunner: CommandRunner;
3
4
  /** Batch launchers need cmd.exe; no free-form user text is accepted as shell arguments. */
4
5
  export declare function runResolvedCommand(runner: CommandRunner, platform: string, file: string, args: readonly string[], env: SetupEnvironment, timeoutMs?: number): Promise<CommandResult>;
@@ -1,35 +1,129 @@
1
- import { execFile } from 'node:child_process';
1
+ import { spawn } from 'node:child_process';
2
+ export const STDERR_TAIL_MAX_BYTES = 4 * 1024;
3
+ const STDOUT_MAX_BYTES = 1024 * 1024;
4
+ class ByteTail {
5
+ buffer = Buffer.alloc(STDERR_TAIL_MAX_BYTES);
6
+ start = 0;
7
+ length = 0;
8
+ truncated = false;
9
+ get didTruncate() {
10
+ return this.truncated;
11
+ }
12
+ push(chunk) {
13
+ if (chunk.length >= STDERR_TAIL_MAX_BYTES) {
14
+ if (chunk.length > STDERR_TAIL_MAX_BYTES || this.length > 0)
15
+ this.truncated = true;
16
+ chunk.copy(this.buffer, 0, chunk.length - STDERR_TAIL_MAX_BYTES);
17
+ this.start = 0;
18
+ this.length = STDERR_TAIL_MAX_BYTES;
19
+ return;
20
+ }
21
+ const overflow = Math.max(0, this.length + chunk.length - STDERR_TAIL_MAX_BYTES);
22
+ if (overflow > 0)
23
+ this.truncated = true;
24
+ this.start = (this.start + overflow) % STDERR_TAIL_MAX_BYTES;
25
+ this.length -= overflow;
26
+ const writeAt = (this.start + this.length) % STDERR_TAIL_MAX_BYTES;
27
+ const firstLength = Math.min(chunk.length, STDERR_TAIL_MAX_BYTES - writeAt);
28
+ chunk.copy(this.buffer, writeAt, 0, firstLength);
29
+ if (firstLength < chunk.length)
30
+ chunk.copy(this.buffer, 0, firstLength);
31
+ this.length += chunk.length;
32
+ }
33
+ toString() {
34
+ const bytes = Buffer.alloc(this.length);
35
+ const firstLength = Math.min(this.length, STDERR_TAIL_MAX_BYTES - this.start);
36
+ this.buffer.copy(bytes, 0, this.start, this.start + firstLength);
37
+ if (firstLength < this.length)
38
+ this.buffer.copy(bytes, firstLength, 0, this.length - firstLength);
39
+ let start = 0;
40
+ while (start < bytes.length) {
41
+ const byte = bytes[start];
42
+ if (byte === undefined || (byte & 0xc0) !== 0x80)
43
+ break;
44
+ start++;
45
+ }
46
+ return bytes.subarray(start).toString('utf8');
47
+ }
48
+ }
2
49
  export const defaultCommandRunner = {
3
50
  run(file, args, options = {}) {
4
51
  return new Promise((resolve) => {
5
52
  const started = performance.now();
6
53
  const timeoutMs = options.timeoutMs ?? 15_000;
7
- execFile(file, [...args], {
8
- env: options.env ?? process.env,
9
- timeout: timeoutMs,
10
- windowsHide: true,
11
- windowsVerbatimArguments: options.windowsVerbatimArguments,
12
- maxBuffer: 1024 * 1024,
13
- }, (error, stdout, stderr) => {
14
- const durationMs = performance.now() - started;
54
+ const stderr = new ByteTail();
55
+ const stdout = [];
56
+ let stdoutLength = 0;
57
+ let outputExceeded = false;
58
+ let spawnError = false;
59
+ let timedOut = false;
60
+ let child;
61
+ try {
62
+ child = spawn(file, [...args], {
63
+ env: options.env ?? process.env,
64
+ windowsHide: true,
65
+ windowsVerbatimArguments: options.windowsVerbatimArguments,
66
+ stdio: ['ignore', 'pipe', 'pipe'],
67
+ });
68
+ }
69
+ catch {
70
+ resolve({
71
+ exitCode: 1,
72
+ stdout: '',
73
+ stderr: '',
74
+ spawnError: true,
75
+ signal: null,
76
+ timedOut: false,
77
+ durationMs: performance.now() - started,
78
+ });
79
+ return;
80
+ }
81
+ const timer = timeoutMs > 0
82
+ ? setTimeout(() => {
83
+ timedOut = true;
84
+ child.kill('SIGTERM');
85
+ }, timeoutMs)
86
+ : undefined;
87
+ child.stdout?.on('data', (chunk) => {
88
+ const remaining = STDOUT_MAX_BYTES - stdoutLength;
89
+ const length = Math.min(remaining, chunk.length);
90
+ if (length > 0) {
91
+ stdout.push(chunk.subarray(0, length));
92
+ stdoutLength += length;
93
+ }
94
+ if (chunk.length > remaining) {
95
+ outputExceeded = true;
96
+ child.kill('SIGTERM');
97
+ }
98
+ });
99
+ child.stderr?.on('data', (chunk) => stderr.push(chunk));
100
+ let settled = false;
101
+ const settle = (code, signal) => {
102
+ if (settled)
103
+ return;
104
+ settled = true;
105
+ if (timer)
106
+ clearTimeout(timer);
15
107
  resolve({
16
- exitCode: error
17
- ? typeof error.code === 'number'
18
- ? error.code
19
- : 1
20
- : 0,
21
- stdout: String(stdout ?? ''),
22
- stderr: String(stderr ?? ''),
23
- signal: error?.signal ?? null,
24
- // Buffer-limit and spawn errors have string codes, not timeout kills.
25
- timedOut: error?.killed === true &&
26
- typeof error.code !== 'string' &&
27
- error.signal === 'SIGTERM' &&
28
- durationMs >= timeoutMs &&
29
- timeoutMs > 0,
30
- durationMs,
108
+ exitCode: spawnError ? 1 : outputExceeded ? 1 : (code ?? 1),
109
+ stdout: Buffer.concat(stdout, stdoutLength).toString('utf8'),
110
+ stderr: stderr.toString(),
111
+ stderrTruncated: stderr.didTruncate,
112
+ ...(spawnError ? { spawnError: true } : {}),
113
+ signal: signal ?? null,
114
+ timedOut,
115
+ durationMs: performance.now() - started,
31
116
  });
117
+ };
118
+ child.once('error', () => {
119
+ spawnError = true;
120
+ // A child that never started (ENOENT, EACCES) has no process for the
121
+ // timer to kill. Node documents no guarantee that 'close' follows that
122
+ // 'error', so settle here rather than wait for it.
123
+ if (child.pid === undefined)
124
+ settle(null, null);
32
125
  });
126
+ child.once('close', (code, signal) => settle(code, signal));
33
127
  });
34
128
  },
35
129
  };
@@ -1,4 +1,5 @@
1
1
  export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
+ export { SetupCommandError } from './command-error.js';
2
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
3
4
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
4
5
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
@@ -1,4 +1,5 @@
1
1
  export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
+ export { SetupCommandError } from './command-error.js';
2
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
3
4
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
4
5
  export { planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
@@ -1,4 +1,5 @@
1
1
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, } from 'jsonc-parser';
2
+ import { SetupCommandError } from './command-error.js';
2
3
  import { defaultCommandRunner, runResolvedCommand } from './command-runner.js';
3
4
  import { writeHostConfigAtomic } from './config-write.js';
4
5
  import { defaultSetupFileSystem } from './detect.js';
@@ -125,6 +126,11 @@ export async function registerOpenCode(writes, beforeWrite) {
125
126
  export async function registerPi(plugin, executable, io = {}) {
126
127
  const { platform, env } = setupPaths(io);
127
128
  const result = await runResolvedCommand(io.runner ?? defaultCommandRunner, platform, executable, ['install', `npm:${plugin.packages.pi}@${plugin.version}`], env);
128
- if (result.exitCode !== 0)
129
- throw new Error('Pi install failed; run pi install after checking your npm connection.');
129
+ if (result.exitCode !== 0 || result.timedOut)
130
+ throw new SetupCommandError({
131
+ exitCode: result.spawnError ? null : result.exitCode,
132
+ signal: result.signal ?? null,
133
+ stderrTail: result.stderr,
134
+ stderrTruncated: result.stderrTruncated ?? false,
135
+ });
130
136
  }
@@ -57,6 +57,8 @@ export interface CommandResult {
57
57
  exitCode: number;
58
58
  stdout: string;
59
59
  stderr: string;
60
+ spawnError?: boolean;
61
+ stderrTruncated?: boolean;
60
62
  signal?: NodeJS.Signals | null;
61
63
  timedOut?: boolean;
62
64
  durationMs?: number;
@@ -42,7 +42,7 @@ export interface OpenPoolStoreOptions {
42
42
  requireCredentialStamps?: boolean;
43
43
  /** Require an exact secret fingerprint for every roster-publication removal. */
44
44
  requireRemovedFingerprint?: boolean;
45
- /** Injected clock for leases, refresh stamps and `addedAt`. */
45
+ /** Logical clock for refresh stamps and `addedAt`; filesystem leases always use wall time. */
46
46
  now?: () => number;
47
47
  /**
48
48
  * Ordered store-lock list held across every read-modify-write. Defaults to
@@ -57,7 +57,6 @@ export function openPoolStore(options) {
57
57
  ],
58
58
  lockDefaults,
59
59
  lockEnv: {
60
- now: options.now ?? Date.now,
61
60
  ...(options.onLockEvent ? { onLockEvent: options.onLockEvent } : {}),
62
61
  ...(options.onLockStep ? { onLockStep: options.onLockStep } : {}),
63
62
  ...(options.onRenewalTimer
@@ -24,7 +24,6 @@ export type LockEvent = {
24
24
  path: string;
25
25
  };
26
26
  export interface LockEnvironment {
27
- now: () => number;
28
27
  onLockEvent?: (event: LockEvent) => void;
29
28
  onLockStep?: (lock: {
30
29
  name: string;
@@ -42,7 +42,6 @@ export async function acquirePoolLock(spec, defaults, env) {
42
42
  name: spec.name,
43
43
  path: spec.path,
44
44
  ttlMs: options.ttlMs,
45
- now: env.now,
46
45
  renew: options.renew,
47
46
  onContended: () => emit('contended'),
48
47
  ...(env.onRenewalTimer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.17.2",
3
+ "version": "0.18.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": {