@cortexkit/common-auth 0.52.0 → 0.53.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.
- package/dist/claustrum/availability.js +1 -1
- package/dist/claustrum/custody.js +1 -1
- package/dist/fs/private-files.js +6 -2
- package/dist/limits/wording.js +7 -1
- package/dist/pi-slot/index.d.ts +1 -1
- package/dist/pi-slot/index.js +1 -1
- package/dist/pi-slot/slot.d.ts +6 -9
- package/dist/pi-slot/slot.js +42 -105
- package/dist/redaction/index.js +6 -0
- package/dist/rpc/index.d.ts +1 -1
- package/dist/rpc/index.js +1 -1
- package/dist/rpc/port-file.d.ts +4 -0
- package/dist/rpc/port-file.js +55 -49
- package/dist/rpc/rpc-server.js +3 -2
- package/dist/rpc/startup-sweep.d.ts +4 -0
- package/dist/rpc/startup-sweep.js +32 -0
- package/package.json +1 -1
|
@@ -94,7 +94,7 @@ export class ClaustrumUnreachableError extends ClaustrumConsumerError {
|
|
|
94
94
|
*/
|
|
95
95
|
reason;
|
|
96
96
|
constructor(reason) {
|
|
97
|
-
super('unavailable', 'Claustrum
|
|
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
|
|
407
|
+
throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation failed');
|
|
408
408
|
}
|
|
409
409
|
finally {
|
|
410
410
|
removeAbortListener?.();
|
package/dist/fs/private-files.js
CHANGED
|
@@ -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
|
|
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
|
});
|
|
@@ -83,7 +85,9 @@ export class PrivateFileError extends Error {
|
|
|
83
85
|
constructor(path, stage, cause) {
|
|
84
86
|
const detail = cause;
|
|
85
87
|
super(detail?.code === 'ERR_PRIVATE_FILES_UNAVAILABLE'
|
|
86
|
-
?
|
|
88
|
+
? // The reason stays on `.reason`: its word "unavailable" would make
|
|
89
|
+
// OpenCode 1 retry a plain error carrying this message.
|
|
90
|
+
`Private file refused at ${stage}: ${path}. The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
|
|
87
91
|
: `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
|
|
88
92
|
this.path = path;
|
|
89
93
|
this.stage = stage;
|
package/dist/limits/wording.js
CHANGED
|
@@ -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
|
-
|
|
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 {
|
package/dist/pi-slot/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Replace a Pi provider login with a vault placeholder without changing provider or model identifiers. */
|
|
2
2
|
export type { PiSlot, PiSlotErrorCode, PiSlotInspection, PiSlotOptions, } from './slot.js';
|
|
3
3
|
export { openPiSlot, PiSlotError } from './slot.js';
|
package/dist/pi-slot/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Replace a Pi provider login with a vault placeholder without changing provider or model identifiers. */
|
|
2
2
|
export { openPiSlot, PiSlotError } from './slot.js';
|
package/dist/pi-slot/slot.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type PiSlotErrorCode = 'invalid-options' | 'invalid-auth' | '
|
|
1
|
+
export type PiSlotErrorCode = 'invalid-options' | 'invalid-auth' | 'unsafe-path' | 'lock-timeout' | 'lock-compromised' | 'io';
|
|
2
2
|
/** Errors deliberately contain neither paths nor credentials nor underlying error messages. */
|
|
3
3
|
export declare class PiSlotError extends Error {
|
|
4
4
|
readonly code: PiSlotErrorCode;
|
|
@@ -10,10 +10,8 @@ export interface PiSlotOptions {
|
|
|
10
10
|
authPath: string;
|
|
11
11
|
provider: string;
|
|
12
12
|
/**
|
|
13
|
-
* Where the
|
|
14
|
-
*
|
|
15
|
-
* stash holds one provider's original login, and a second provider writing
|
|
16
|
-
* to it would overwrite the first one's backup.
|
|
13
|
+
* Where older versions kept the original Pi login; deleted when found.
|
|
14
|
+
* Keep the same path across upgrades so legacy credentials can be removed.
|
|
17
15
|
*/
|
|
18
16
|
stashPath: string;
|
|
19
17
|
/**
|
|
@@ -26,13 +24,12 @@ export interface PiSlotOptions {
|
|
|
26
24
|
lockTimeoutMs?: number;
|
|
27
25
|
}
|
|
28
26
|
export interface PiSlotInspection {
|
|
29
|
-
slot: 'original' | 'placeholder' | '
|
|
30
|
-
stash: 'valid' | 'missing';
|
|
27
|
+
slot: 'original' | 'placeholder' | 'empty';
|
|
31
28
|
}
|
|
32
29
|
export interface PiSlot {
|
|
33
30
|
inspect(): Promise<PiSlotInspection>;
|
|
34
31
|
enterVault(): Promise<void>;
|
|
35
|
-
exitVault(): Promise<'
|
|
32
|
+
exitVault(): Promise<'cleared' | 'nothing-to-do'>;
|
|
36
33
|
}
|
|
37
34
|
/**
|
|
38
35
|
* Production entry point. Pi caches which models are usable; after a
|
|
@@ -44,7 +41,7 @@ export declare function openPiSlot(options: PiSlotOptions): PiSlot;
|
|
|
44
41
|
* Internal test entry point: pause reads, renewals, or renames to simulate races,
|
|
45
42
|
* and observe durable writes/deletion to simulate crashes. Not a public export.
|
|
46
43
|
*/
|
|
47
|
-
export declare function createPiSlot(options: PiSlotOptions, onStep?: (step: '
|
|
44
|
+
export declare function createPiSlot(options: PiSlotOptions, onStep?: (step: 'auth-written' | 'stash-deleted') => void, hooks?: {
|
|
48
45
|
afterReadCheck?: (path: string) => Promise<void>;
|
|
49
46
|
onRenew?: (renew: () => Promise<void>) => void;
|
|
50
47
|
beforeRename?: (path: string) => Promise<void>;
|
package/dist/pi-slot/slot.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
1
|
import { constants } from 'node:fs';
|
|
3
2
|
import { lstat, mkdir, open, unlink } from 'node:fs/promises';
|
|
4
3
|
import { dirname, resolve } from 'node:path';
|
|
5
4
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
6
5
|
import { writeJsonAtomic } from '../fs/atomic-write.js';
|
|
7
|
-
import { ensurePrivateDirectory, PrivateFileError, readPrivateBuffer, windowsPrivateFiles, } from '../fs/private-files.js';
|
|
6
|
+
import { ensurePrivateDirectory, PrivateFileError, readPrivateBuffer, verifySafeDirectory, windowsPrivateFiles, } from '../fs/private-files.js';
|
|
8
7
|
import { acquirePiLock } from './lock.js';
|
|
9
8
|
/** Errors deliberately contain neither paths nor credentials nor underlying error messages. */
|
|
10
9
|
export class PiSlotError extends Error {
|
|
@@ -79,31 +78,17 @@ function rootSpans(text) {
|
|
|
79
78
|
function object(value) {
|
|
80
79
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
81
80
|
}
|
|
82
|
-
function canonical(value) {
|
|
83
|
-
if (Array.isArray(value))
|
|
84
|
-
return `[${value.map(canonical).join(',')}]`;
|
|
85
|
-
if (object(value)) {
|
|
86
|
-
return `{${Object.keys(value)
|
|
87
|
-
.sort()
|
|
88
|
-
.map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
|
|
89
|
-
.join(',')}}`;
|
|
90
|
-
}
|
|
91
|
-
return JSON.stringify(value);
|
|
92
|
-
}
|
|
93
|
-
function digest(value) {
|
|
94
|
-
return createHash('sha256').update(canonical(value)).digest('hex');
|
|
95
|
-
}
|
|
96
81
|
function code(error) {
|
|
97
82
|
return object(error) ? error.code : undefined;
|
|
98
83
|
}
|
|
99
|
-
async function safeRead(path,
|
|
84
|
+
async function safeRead(path, afterReadCheck) {
|
|
100
85
|
if (windowsPrivateFiles) {
|
|
101
86
|
try {
|
|
102
87
|
await afterReadCheck?.(path);
|
|
103
88
|
const bytes = await readPrivateBuffer(path, true);
|
|
104
89
|
const text = bytes.toString('utf8');
|
|
105
90
|
if (!bytes.equals(Buffer.from(text)))
|
|
106
|
-
throw new PiSlotError(
|
|
91
|
+
throw new PiSlotError('invalid-auth');
|
|
107
92
|
return text;
|
|
108
93
|
}
|
|
109
94
|
catch (error) {
|
|
@@ -116,7 +101,7 @@ async function safeRead(path, privateFile = false, afterReadCheck) {
|
|
|
116
101
|
try {
|
|
117
102
|
file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
118
103
|
const stat = await file.stat();
|
|
119
|
-
if (!stat.isFile()
|
|
104
|
+
if (!stat.isFile()) {
|
|
120
105
|
throw new PiSlotError('unsafe-path');
|
|
121
106
|
}
|
|
122
107
|
await afterReadCheck?.(path);
|
|
@@ -130,7 +115,7 @@ async function safeRead(path, privateFile = false, afterReadCheck) {
|
|
|
130
115
|
const bytes = await file.readFile();
|
|
131
116
|
const text = bytes.toString('utf8');
|
|
132
117
|
if (!bytes.equals(Buffer.from(text))) {
|
|
133
|
-
throw new PiSlotError(
|
|
118
|
+
throw new PiSlotError('invalid-auth');
|
|
134
119
|
}
|
|
135
120
|
return text;
|
|
136
121
|
}
|
|
@@ -169,12 +154,6 @@ function parseAuth(text, provider) {
|
|
|
169
154
|
throw new PiSlotError('invalid-auth');
|
|
170
155
|
}
|
|
171
156
|
}
|
|
172
|
-
function entryText(auth) {
|
|
173
|
-
const value = auth.property?.value;
|
|
174
|
-
return value
|
|
175
|
-
? auth.text.slice(value.offset, value.offset + value.length)
|
|
176
|
-
: null;
|
|
177
|
-
}
|
|
178
157
|
function replaceEntry(auth, provider, next) {
|
|
179
158
|
const { text, root, property } = auth;
|
|
180
159
|
const properties = root.children ?? [];
|
|
@@ -199,7 +178,7 @@ function replaceEntry(auth, provider, next) {
|
|
|
199
178
|
if (next === null)
|
|
200
179
|
return text;
|
|
201
180
|
const last = properties.at(-1);
|
|
202
|
-
// Insert next to the last value
|
|
181
|
+
// Insert next to the last value so removal preserves the surrounding whitespace.
|
|
203
182
|
const offset = last ? last.offset + last.length : root.offset + 1;
|
|
204
183
|
return `${text.slice(0, offset)}${last ? ',' : ''}${JSON.stringify(provider)}:${next}${text.slice(offset)}`;
|
|
205
184
|
}
|
|
@@ -257,34 +236,11 @@ export function createPiSlot(options, onStep, hooks) {
|
|
|
257
236
|
if (authPath === stashPath || stashPath === `${authPath}.lock`) {
|
|
258
237
|
throw new PiSlotError('invalid-options');
|
|
259
238
|
}
|
|
260
|
-
const authIdentity = digest(authPath);
|
|
261
|
-
const placeholderIdentity = digest(placeholderKey);
|
|
262
239
|
const placeholder = { type: 'api_key', key: placeholderKey };
|
|
263
|
-
const isPlaceholder = (entry) =>
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
return undefined;
|
|
268
|
-
try {
|
|
269
|
-
const stash = JSON.parse(text);
|
|
270
|
-
if (stash.version !== 1 ||
|
|
271
|
-
stash.provider !== provider ||
|
|
272
|
-
stash.authIdentity !== authIdentity ||
|
|
273
|
-
stash.placeholderIdentity !== placeholderIdentity ||
|
|
274
|
-
(stash.entry !== null && !object(stash.entry)) ||
|
|
275
|
-
stash.sha256 !== digest(stash.entry) ||
|
|
276
|
-
(stash.entry === null
|
|
277
|
-
? stash.entryJson !== null
|
|
278
|
-
: typeof stash.entryJson !== 'string' ||
|
|
279
|
-
digest(JSON.parse(stash.entryJson)) !== stash.sha256)) {
|
|
280
|
-
throw new Error();
|
|
281
|
-
}
|
|
282
|
-
return stash;
|
|
283
|
-
}
|
|
284
|
-
catch {
|
|
285
|
-
throw new PiSlotError('invalid-stash');
|
|
286
|
-
}
|
|
287
|
-
}
|
|
240
|
+
const isPlaceholder = (entry) => entry !== null &&
|
|
241
|
+
Object.keys(entry).length === 2 &&
|
|
242
|
+
entry.type === placeholder.type &&
|
|
243
|
+
entry.key === placeholder.key;
|
|
288
244
|
async function locked(fn) {
|
|
289
245
|
let release;
|
|
290
246
|
let assertFresh;
|
|
@@ -334,11 +290,27 @@ export function createPiSlot(options, onStep, hooks) {
|
|
|
334
290
|
}
|
|
335
291
|
}
|
|
336
292
|
async function load() {
|
|
337
|
-
|
|
338
|
-
const stash = await loadStash();
|
|
339
|
-
return { auth, stash };
|
|
293
|
+
return parseAuth((await safeRead(authPath, hooks?.afterReadCheck)) ?? '{}', provider);
|
|
340
294
|
}
|
|
341
295
|
async function deleteStash(assertLock) {
|
|
296
|
+
// Legacy credentials are discarded without opening or parsing their contents.
|
|
297
|
+
try {
|
|
298
|
+
const file = await lstat(stashPath);
|
|
299
|
+
if (!file.isFile())
|
|
300
|
+
throw new PiSlotError('unsafe-path');
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
if (code(error) === 'ENOENT')
|
|
304
|
+
return;
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
if (windowsPrivateFiles)
|
|
308
|
+
await verifySafeDirectory(dirname(stashPath));
|
|
309
|
+
else {
|
|
310
|
+
const dir = await lstat(dirname(stashPath));
|
|
311
|
+
if (!dir.isDirectory() || (dir.mode & 0o777) !== 0o700)
|
|
312
|
+
throw new PiSlotError('unsafe-path');
|
|
313
|
+
}
|
|
342
314
|
assertLock();
|
|
343
315
|
await unlink(stashPath);
|
|
344
316
|
await syncDir(dirname(stashPath));
|
|
@@ -346,66 +318,31 @@ export function createPiSlot(options, onStep, hooks) {
|
|
|
346
318
|
}
|
|
347
319
|
return {
|
|
348
320
|
inspect: () => locked(async () => {
|
|
349
|
-
const
|
|
321
|
+
const auth = await load();
|
|
350
322
|
const slot = isPlaceholder(auth.entry)
|
|
351
323
|
? 'placeholder'
|
|
352
324
|
: auth.entry === null
|
|
353
325
|
? 'empty'
|
|
354
|
-
:
|
|
355
|
-
|
|
356
|
-
: 'foreign';
|
|
357
|
-
return { slot, stash: stash ? 'valid' : 'missing' };
|
|
326
|
+
: 'original';
|
|
327
|
+
return { slot };
|
|
358
328
|
}),
|
|
359
329
|
enterVault: () => locked(async (assertLock) => {
|
|
360
|
-
const
|
|
361
|
-
if (isPlaceholder(auth.entry)) {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
return;
|
|
365
|
-
}
|
|
366
|
-
if (stash && digest(auth.entry) !== stash.sha256)
|
|
367
|
-
throw new PiSlotError('conflict');
|
|
368
|
-
if (!stash) {
|
|
369
|
-
if (windowsPrivateFiles)
|
|
370
|
-
await ensurePrivateDirectory(dirname(stashPath));
|
|
371
|
-
else {
|
|
372
|
-
await mkdir(dirname(stashPath), { recursive: true, mode: 0o700 });
|
|
373
|
-
const dir = await lstat(dirname(stashPath));
|
|
374
|
-
if (!dir.isDirectory() || (dir.mode & 0o777) !== 0o700)
|
|
375
|
-
throw new PiSlotError('unsafe-path');
|
|
376
|
-
}
|
|
377
|
-
const saved = {
|
|
378
|
-
version: 1,
|
|
379
|
-
provider,
|
|
380
|
-
authIdentity,
|
|
381
|
-
placeholderIdentity,
|
|
382
|
-
entry: auth.entry,
|
|
383
|
-
entryJson: entryText(auth),
|
|
384
|
-
sha256: digest(auth.entry),
|
|
385
|
-
};
|
|
386
|
-
await atomicWrite(stashPath, JSON.stringify(saved), assertLock, hooks?.beforeRename);
|
|
387
|
-
onStep?.('stash-written');
|
|
330
|
+
const auth = await load();
|
|
331
|
+
if (!isPlaceholder(auth.entry)) {
|
|
332
|
+
await atomicWrite(authPath, replaceEntry(auth, provider, JSON.stringify(placeholder)), assertLock, hooks?.beforeRename);
|
|
333
|
+
onStep?.('auth-written');
|
|
388
334
|
}
|
|
389
|
-
await
|
|
390
|
-
onStep?.('auth-written');
|
|
335
|
+
await deleteStash(assertLock);
|
|
391
336
|
}),
|
|
392
337
|
exitVault: () => locked(async (assertLock) => {
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
return 'nothing-to-do';
|
|
398
|
-
}
|
|
399
|
-
if (isPlaceholder(auth.entry)) {
|
|
400
|
-
await atomicWrite(authPath, replaceEntry(auth, provider, stash.entryJson), assertLock, hooks?.beforeRename);
|
|
338
|
+
const auth = await load();
|
|
339
|
+
const cleared = isPlaceholder(auth.entry);
|
|
340
|
+
if (cleared) {
|
|
341
|
+
await atomicWrite(authPath, replaceEntry(auth, provider, null), assertLock, hooks?.beforeRename);
|
|
401
342
|
onStep?.('auth-written');
|
|
402
343
|
}
|
|
403
|
-
else if (digest(auth.entry) !== stash.sha256) {
|
|
404
|
-
return 'conflict';
|
|
405
|
-
}
|
|
406
|
-
// Also completes a restore interrupted between the auth rename and stash deletion.
|
|
407
344
|
await deleteStash(assertLock);
|
|
408
|
-
return '
|
|
345
|
+
return cleared ? 'cleared' : 'nothing-to-do';
|
|
409
346
|
}),
|
|
410
347
|
};
|
|
411
348
|
}
|
package/dist/redaction/index.js
CHANGED
|
@@ -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);
|
package/dist/rpc/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export * from './notifications.js';
|
|
2
|
-
export
|
|
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
|
|
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';
|
package/dist/rpc/port-file.d.ts
CHANGED
|
@@ -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
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -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
|
|
98
|
-
//
|
|
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
|
-
|
|
140
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
190
|
+
raw = await readPrivateText(portFile);
|
|
169
191
|
}
|
|
170
192
|
catch (error) {
|
|
171
|
-
if (error.code
|
|
172
|
-
|
|
173
|
-
|
|
193
|
+
if (error instanceof PrivateFileError && error.code !== 'ENOENT')
|
|
194
|
+
throw error;
|
|
195
|
+
continue;
|
|
174
196
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
-
|
|
210
|
-
await
|
|
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 = {}) {
|
package/dist/rpc/rpc-server.js
CHANGED
|
@@ -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 {
|
|
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
|
|
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.
|
|
3
|
+
"version": "0.53.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": {
|