@cortexkit/common-auth 0.52.1 → 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.
@@ -85,7 +85,9 @@ export class PrivateFileError extends Error {
85
85
  constructor(path, stage, cause) {
86
86
  const detail = cause;
87
87
  super(detail?.code === 'ERR_PRIVATE_FILES_UNAVAILABLE'
88
- ? `Private file refused at ${stage}: ${path} (${PRIVATE_FILES_UNAVAILABLE_REASON}). 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.`
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.`
89
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 });
90
92
  this.path = path;
91
93
  this.stage = stage;
@@ -1,3 +1,3 @@
1
- /** Move a Pi provider slot aside without changing provider or model identifiers. */
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';
@@ -1,2 +1,2 @@
1
- /** Move a Pi provider slot aside without changing provider or model identifiers. */
1
+ /** Replace a Pi provider login with a vault placeholder without changing provider or model identifiers. */
2
2
  export { openPiSlot, PiSlotError } from './slot.js';
@@ -1,4 +1,4 @@
1
- export type PiSlotErrorCode = 'invalid-options' | 'invalid-auth' | 'invalid-stash' | 'unsafe-path' | 'missing-stash' | 'conflict' | 'lock-timeout' | 'lock-compromised' | 'io';
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 provider's original Pi login is kept while the vault serves.
14
- * Put it in a private directory, and give each provider its own file: one
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' | 'foreign' | 'empty';
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<'restored' | 'conflict' | 'nothing-to-do'>;
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: 'stash-written' | 'auth-written' | 'stash-deleted') => void, hooks?: {
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>;
@@ -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, privateFile = false, afterReadCheck) {
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(privateFile ? 'invalid-stash' : 'invalid-auth');
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() || (privateFile && (stat.mode & 0o777) !== 0o600)) {
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(privateFile ? 'invalid-stash' : 'invalid-auth');
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, not after its whitespace, so deletion reverses an empty-slot swap.
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) => digest(entry) === digest(placeholder);
264
- async function loadStash() {
265
- const text = await safeRead(stashPath, true, hooks?.afterReadCheck);
266
- if (text === undefined)
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
- const auth = parseAuth((await safeRead(authPath, false, hooks?.afterReadCheck)) ?? '{}', provider);
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 { auth, stash } = await load();
321
+ const auth = await load();
350
322
  const slot = isPlaceholder(auth.entry)
351
323
  ? 'placeholder'
352
324
  : auth.entry === null
353
325
  ? 'empty'
354
- : !stash || digest(auth.entry) === stash.sha256
355
- ? 'original'
356
- : 'foreign';
357
- return { slot, stash: stash ? 'valid' : 'missing' };
326
+ : 'original';
327
+ return { slot };
358
328
  }),
359
329
  enterVault: () => locked(async (assertLock) => {
360
- const { auth, stash } = await load();
361
- if (isPlaceholder(auth.entry)) {
362
- if (!stash)
363
- throw new PiSlotError('missing-stash');
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 atomicWrite(authPath, replaceEntry(auth, provider, JSON.stringify(placeholder)), assertLock, hooks?.beforeRename);
390
- onStep?.('auth-written');
335
+ await deleteStash(assertLock);
391
336
  }),
392
337
  exitVault: () => locked(async (assertLock) => {
393
- const { auth, stash } = await load();
394
- if (!stash) {
395
- if (isPlaceholder(auth.entry))
396
- throw new PiSlotError('missing-stash');
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 'restored';
345
+ return cleared ? 'cleared' : 'nothing-to-do';
409
346
  }),
410
347
  };
411
348
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.52.1",
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": {