@cortexkit/common-auth 0.52.0 → 0.52.1

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.
@@ -94,7 +94,7 @@ export class ClaustrumUnreachableError extends ClaustrumConsumerError {
94
94
  */
95
95
  reason;
96
96
  constructor(reason) {
97
- super('unavailable', 'Claustrum scoped operation unavailable');
97
+ super('unavailable', 'Claustrum vault could not be reached');
98
98
  this.name = 'ClaustrumUnreachableError';
99
99
  if (reason === 'host-accessor-missing' || reason === 'host-accessor-failed')
100
100
  this.reason = reason;
@@ -404,7 +404,7 @@ export class ClaustrumScopedCustody {
404
404
  throw error;
405
405
  if (classifyVaultFailure(error) === 'unreachable')
406
406
  throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
407
- throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation unavailable');
407
+ throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation failed');
408
408
  }
409
409
  finally {
410
410
  removeAbortListener?.();
@@ -24,7 +24,9 @@ export function setPrivateFilesBackendForTest(api) {
24
24
  /** The fixed `reason` of a refusal because the Windows native addon did not load. */
25
25
  export const PRIVATE_FILES_UNAVAILABLE_REASON = 'native-addon-unavailable';
26
26
  function privateFilesUnavailable(cause) {
27
- return Object.assign(new Error('Windows private-files native addon is unavailable', { cause }), {
27
+ return Object.assign(new Error('Windows private-files native addon could not be loaded', {
28
+ cause,
29
+ }), {
28
30
  code: 'ERR_PRIVATE_FILES_UNAVAILABLE',
29
31
  reason: PRIVATE_FILES_UNAVAILABLE_REASON,
30
32
  });
@@ -64,7 +64,13 @@ const pi140Pattern = new RegExp([
64
64
  'subscription_sharing_user_unavailable',
65
65
  ].join('|'), 'i');
66
66
  export function hasUnsafeWording(text) {
67
- return (openCode1Patterns.some((pattern) => pattern.test(text)) ||
67
+ // OpenCode 1's session/retry.ts non-API-error branch retries when any of
68
+ // these substrings occurs in the message, even without a retryable flag.
69
+ const lower = text.toLowerCase();
70
+ return (lower.includes('too_many_requests') ||
71
+ lower.includes('exhausted') ||
72
+ lower.includes('unavailable') ||
73
+ openCode1Patterns.some((pattern) => pattern.test(text)) ||
68
74
  pi140Pattern.test(text));
69
75
  }
70
76
  export class UnsafeWordingError extends Error {
@@ -123,6 +123,9 @@ const retryBodyPatterns = [
123
123
  /try your request again|retry your request|resource exhausted|resource_exhausted/i,
124
124
  /\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i,
125
125
  ];
126
+ // OpenCode 1's session/retry.ts non-API-error branch also retries these
127
+ // substrings. Preserve them when compacting diagnostic bodies too.
128
+ const nonApiRetryPattern = /too_many_requests|exhausted|unavailable/i;
126
129
  /** Numeric request ids are quoted from their source lexeme, not a rounded JS number. */
127
130
  function requestIdFromBody(body) {
128
131
  try {
@@ -179,6 +182,9 @@ function projectResponseBody(body, credential) {
179
182
  if (Buffer.byteLength(safe, 'utf8') <= responseBodyLimit)
180
183
  return safe;
181
184
  const markers = retryBodyPatterns.flatMap((pattern) => pattern.exec(safe)?.[0] ?? []);
185
+ const nonApiMarker = nonApiRetryPattern.exec(safe)?.[0];
186
+ if (nonApiMarker)
187
+ markers.push(nonApiMarker);
182
188
  for (const marker of ['FreeUsageLimitError', 'GoUsageLimitError']) {
183
189
  if (safe.includes(marker))
184
190
  markers.push(marker);
@@ -1,5 +1,5 @@
1
1
  export * from './notifications.js';
2
- export * from './port-file.js';
2
+ export { createManagedRpcStateDirPredicate, type DiscoverPortFileOptions, discoverPortFile, getRpcDir, isManagedRpcStateDir, type PortFileEntry, portFileIdentity, sweepRpcState, writePortFile, } from './port-file.js';
3
3
  export * from './rpc-client.js';
4
4
  export * from './rpc-server.js';
5
5
  export * from './server-registry.js';
package/dist/rpc/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from './notifications.js';
2
- export * from './port-file.js';
2
+ export { createManagedRpcStateDirPredicate, discoverPortFile, getRpcDir, isManagedRpcStateDir, portFileIdentity, sweepRpcState, writePortFile, } from './port-file.js';
3
3
  export * from './rpc-client.js';
4
4
  export * from './rpc-server.js';
5
5
  export * from './server-registry.js';
@@ -27,6 +27,10 @@ export declare function sweepRpcState(root: string, activeDir: string, isManaged
27
27
  /** Internal seam for replacing a stale record before its identity recheck. */
28
28
  beforeRemove?: (path: string) => void | Promise<void>;
29
29
  }): Promise<void>;
30
+ /** Internal folder cleanup shared by full and throttled startup sweeps. */
31
+ export declare function sweepRpcDirectory(dir: string, log?: RpcLogChannel, options?: PortFileClock & {
32
+ beforeRemove?: (path: string) => void | Promise<void>;
33
+ }, cutoff?: number): Promise<boolean>;
30
34
  export interface DiscoverPortFileOptions extends PortFileClock {
31
35
  /**
32
36
  * Return only the expected PID's entry, or null; never fall back to
@@ -94,9 +94,8 @@ async function removeCorruptPortFile(portFile, log) {
94
94
  export async function writePortFile(dir, entry, options = {}) {
95
95
  // The directory can be removed by another project's sweep between our
96
96
  // mkdir and the first open/rename, so the whole create-then-rename
97
- // unit is retried once on ENOENT. The retry recreates the directory; a
98
- // persistent ENOENT (e.g. permission, read-only parent) will surface on
99
- // the second attempt — failing fast beats an unbounded loop.
97
+ // unit gets up to five attempts on ENOENT. Each retry recreates the
98
+ // directory after a short delay, but persistent removal still surfaces.
100
99
  const writeOnce = async () => {
101
100
  const target = join(dir, `port-${entry.pid}.json`);
102
101
  if (windowsPrivateFiles) {
@@ -136,14 +135,15 @@ export async function writePortFile(dir, entry, options = {}) {
136
135
  }
137
136
  return target;
138
137
  };
139
- try {
140
- return await writeOnce();
141
- }
142
- catch (error) {
143
- if (error.code === 'ENOENT') {
138
+ for (let attempt = 1;; attempt += 1) {
139
+ try {
144
140
  return await writeOnce();
145
141
  }
146
- throw error;
142
+ catch (error) {
143
+ if (error.code !== 'ENOENT' || attempt === 5)
144
+ throw error;
145
+ await new Promise((resolve) => setTimeout(resolve, 25));
146
+ }
147
147
  }
148
148
  }
149
149
  export async function sweepRpcState(root, activeDir, isManagedDir, log, options = {}) {
@@ -163,52 +163,58 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log, options
163
163
  continue;
164
164
  }
165
165
  const dir = join(root, projectDir.name);
166
- let names;
166
+ if (!(await sweepRpcDirectory(dir, log, options, cutoff)))
167
+ continue;
168
+ if (resolve(dir) !== active)
169
+ await rmdir(dir).catch(() => { });
170
+ }
171
+ }
172
+ /** Internal folder cleanup shared by full and throttled startup sweeps. */
173
+ export async function sweepRpcDirectory(dir, log, options = {}, cutoff = staleBefore(options)) {
174
+ let names;
175
+ try {
176
+ names = await readdir(dir);
177
+ }
178
+ catch (error) {
179
+ if (error.code === 'ENOENT')
180
+ return false;
181
+ throw error;
182
+ }
183
+ for (const name of names) {
184
+ if (!name.startsWith('port-') || !name.endsWith('.json'))
185
+ continue;
186
+ const portFile = join(dir, name);
187
+ const info = await stat(portFile).catch(() => undefined);
188
+ let raw;
167
189
  try {
168
- names = await readdir(dir);
190
+ raw = await readPrivateText(portFile);
169
191
  }
170
192
  catch (error) {
171
- if (error.code === 'ENOENT')
172
- continue;
173
- throw error;
193
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
194
+ throw error;
195
+ continue;
174
196
  }
175
- for (const name of names) {
176
- if (!name.startsWith('port-') || !name.endsWith('.json'))
177
- continue;
178
- const portFile = join(dir, name);
179
- const info = await stat(portFile).catch(() => undefined);
180
- let raw;
181
- try {
182
- raw = await readPrivateText(portFile);
183
- }
184
- catch (error) {
185
- if (error instanceof PrivateFileError && error.code !== 'ENOENT')
186
- throw error;
187
- continue;
188
- }
189
- if (raw === undefined)
190
- continue;
191
- let parsed;
192
- try {
193
- parsed = JSON.parse(raw);
194
- }
195
- catch {
196
- await removeCorruptPortFile(portFile, log);
197
- continue;
198
- }
199
- if (!isUsablePortFileEntry(parsed, name)) {
200
- await removeCorruptPortFile(portFile, log);
201
- continue;
202
- }
203
- const entry = parsed;
204
- if (!pidAlive(entry.pid))
205
- await unlink(portFile).catch(() => { });
206
- else if (isStalePortFile(entry, info, cutoff))
207
- await removeStalePortFile(portFile, raw, info, options.beforeRemove);
197
+ if (raw === undefined)
198
+ continue;
199
+ let parsed;
200
+ try {
201
+ parsed = JSON.parse(raw);
208
202
  }
209
- if (resolve(dir) !== active)
210
- await rmdir(dir).catch(() => { });
203
+ catch {
204
+ await removeCorruptPortFile(portFile, log);
205
+ continue;
206
+ }
207
+ if (!isUsablePortFileEntry(parsed, name)) {
208
+ await removeCorruptPortFile(portFile, log);
209
+ continue;
210
+ }
211
+ const entry = parsed;
212
+ if (!pidAlive(entry.pid))
213
+ await unlink(portFile).catch(() => { });
214
+ else if (isStalePortFile(entry, info, cutoff))
215
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
211
216
  }
217
+ return true;
212
218
  }
213
219
  /** Internal cache validation: probe only the selected file and its PID. */
214
220
  export async function portFileIdentity(dir, entry, options = {}) {
@@ -4,7 +4,8 @@ import { createServer, } from 'node:http';
4
4
  import { join } from 'node:path';
5
5
  import { PrivateFileError, readPrivateText } from '../fs/private-files.js';
6
6
  import { isSessionId, } from './notifications.js';
7
- import { sweepRpcState, writePortFile } from './port-file.js';
7
+ import { writePortFile } from './port-file.js';
8
+ import { sweepRpcStateOnStart } from './startup-sweep.js';
8
9
  /**
9
10
  * Thrown by an `apply`, `drain`, or `parsePending` handler to refuse a request with a 4xx
10
11
  * status. Its message is sent on the wire as `{error: message}`, so it must
@@ -279,7 +280,7 @@ export async function startRpcServer(options) {
279
280
  server.unref();
280
281
  if (options.sweepRoot) {
281
282
  try {
282
- await sweepRpcState(options.sweepRoot, options.dir, options.isManagedDir, log);
283
+ await sweepRpcStateOnStart(options.sweepRoot, options.dir, options.isManagedDir, log);
283
284
  }
284
285
  catch (error) {
285
286
  log.warn('rpc state sweep failed', {
@@ -0,0 +1,4 @@
1
+ import type { RpcLogChannel } from './index.js';
2
+ /** Internal clock seam; reset the process-wide budget between tests. */
3
+ export declare function resetRpcSweepForTest(clock?: () => number): void;
4
+ export declare function sweepRpcStateOnStart(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log: RpcLogChannel): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { basename, dirname, resolve } from 'node:path';
3
+ import { sweepRpcDirectory, sweepRpcState } from './port-file.js';
4
+ const globals = globalThis;
5
+ const key = Symbol.for('common-auth.rpc.startup-sweep');
6
+ globals[key] ??= {};
7
+ const state = globals[key];
8
+ let now = Date.now;
9
+ /** Internal clock seam; reset the process-wide budget between tests. */
10
+ export function resetRpcSweepForTest(clock = Date.now) {
11
+ now = clock;
12
+ delete state.lastSweepAt;
13
+ }
14
+ export async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log) {
15
+ const time = now();
16
+ if (state.lastSweepAt !== undefined && time - state.lastSweepAt < 60_000) {
17
+ // The starting folder still needs corrupt, dead and pre-boot records removed.
18
+ const active = resolve(activeDir);
19
+ if (dirname(active) === resolve(root) &&
20
+ isManagedDir(basename(active)) &&
21
+ (await lstat(active).catch((error) => {
22
+ if (error.code !== 'ENOENT')
23
+ throw error;
24
+ return undefined;
25
+ }))?.isDirectory())
26
+ await sweepRpcDirectory(active, log);
27
+ return;
28
+ }
29
+ // Claim before awaiting I/O so concurrent starts cannot all scan sibling folders.
30
+ state.lastSweepAt = time;
31
+ await sweepRpcState(root, activeDir, isManagedDir, log);
32
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.52.0",
3
+ "version": "0.52.1",
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": {