@cortexkit/common-auth 0.27.1 → 0.29.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.
@@ -107,6 +107,15 @@ export interface EnrollmentAncestorOptions {
107
107
  * sticky ancestors are accepted. Windows uses the shared safe-parent policy.
108
108
  */
109
109
  export declare function refuseWritableAncestor(parent: string, options?: EnrollmentAncestorOptions): Promise<void>;
110
+ /**
111
+ * Create `directory` owner-only, or make an existing one owner-only. POSIX:
112
+ * every component it creates gets mode 0700, a directory another user owns is
113
+ * refused, and one that group or others can reach is tightened to 0700.
114
+ * Windows: private-files creates missing components owner-only and verifies
115
+ * existing ones without modifying them. `what` names the directory in the
116
+ * ownership refusal.
117
+ */
118
+ export declare function ensureClaustrumPrivateDirectory(directory: string, options?: EnrollmentAncestorOptions, what?: string): Promise<void>;
110
119
  export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentStatus>;
111
120
  /**
112
121
  * Resolve the host's account mode from its enrollment files. It never changes
@@ -358,8 +358,15 @@ export async function refuseWritableAncestor(parent, options = {}) {
358
358
  throw new ClaustrumConsumerError('unsafe-file', `Claustrum enrollment parent refused: ${error.path} (${error.reason ?? error.code}). Use a folder that other users cannot write or replace.`);
359
359
  }
360
360
  }
361
- /** POSIX tightens the enrollment directory to 0700; Windows verifies safe ancestry without modifying existing parents. */
362
- async function ensurePrivateDirectory(directory, options = {}) {
361
+ /**
362
+ * Create `directory` owner-only, or make an existing one owner-only. POSIX:
363
+ * every component it creates gets mode 0700, a directory another user owns is
364
+ * refused, and one that group or others can reach is tightened to 0700.
365
+ * Windows: private-files creates missing components owner-only and verifies
366
+ * existing ones without modifying them. `what` names the directory in the
367
+ * ownership refusal.
368
+ */
369
+ export async function ensureClaustrumPrivateDirectory(directory, options = {}, what = 'enrollment directory') {
363
370
  if (windowsPrivateFiles) {
364
371
  await ensureWindowsDirectory(directory, false, ancestorPolicyOptions(options));
365
372
  return;
@@ -368,14 +375,14 @@ async function ensurePrivateDirectory(directory, options = {}) {
368
375
  const metadata = await stat(directory);
369
376
  const uid = process.geteuid?.();
370
377
  if (uid !== undefined && metadata.uid !== uid) {
371
- throw new ClaustrumConsumerError('unsafe-file', 'Claustrum enrollment directory must be owned by the current user');
378
+ throw new ClaustrumConsumerError('unsafe-file', `Claustrum ${what} must be owned by the current user`);
372
379
  }
373
380
  if ((metadata.mode & 0o077) !== 0)
374
381
  await chmod(directory, 0o700);
375
382
  }
376
383
  async function writeStateAtomic(path, state, ancestorOptions = {}) {
377
384
  const parent = dirname(path);
378
- await ensurePrivateDirectory(parent, ancestorOptions);
385
+ await ensureClaustrumPrivateDirectory(parent, ancestorOptions);
379
386
  await refuseWritableAncestor(parent, ancestorOptions);
380
387
  const bytes = `${JSON.stringify(state)}\n`;
381
388
  if (Buffer.byteLength(bytes) > ENROLLMENT_FILE_MAX_BYTES) {
@@ -578,7 +585,7 @@ export class ClaustrumEnrollmentManager {
578
585
  return statusFromState(blocked);
579
586
  }
580
587
  async reconcile() {
581
- await ensurePrivateDirectory(dirname(this.#paths.statePath), this.#ancestorOptions);
588
+ await ensureClaustrumPrivateDirectory(dirname(this.#paths.statePath), this.#ancestorOptions);
582
589
  const lock = await acquireRefreshFileLock({
583
590
  name: 'ceremony',
584
591
  path: this.#paths.statePath,
@@ -715,7 +722,7 @@ export class ClaustrumEnrollmentManager {
715
722
  }
716
723
  // The vault returns the token exactly once: it reaches disk before the
717
724
  // pending metadata (and its secret) is replaced.
718
- await ensurePrivateDirectory(dirname(this.#paths.tokenPath), this.#ancestorOptions);
725
+ await ensureClaustrumPrivateDirectory(dirname(this.#paths.tokenPath), this.#ancestorOptions);
719
726
  await refuseWritableAncestor(dirname(this.#paths.tokenPath), this.#ancestorOptions);
720
727
  await this.#writeTokenFile(this.#paths.tokenPath, {
721
728
  token: outcome.token,
@@ -754,7 +761,7 @@ export class ClaustrumEnrollmentManager {
754
761
  }
755
762
  /** Reset local terminal metadata without connecting to the credential daemon. */
756
763
  export async function resetClaustrumEnrollmentState(paths, proposedName) {
757
- await ensurePrivateDirectory(dirname(paths.statePath));
764
+ await ensureClaustrumPrivateDirectory(dirname(paths.statePath));
758
765
  const lock = await acquireRefreshFileLock({
759
766
  name: 'ceremony',
760
767
  path: paths.statePath,
@@ -817,7 +824,7 @@ async function removeIfPresent(path) {
817
824
  * wrong owner, not owner-only) refuses with `unsafe-file` and both files stay.
818
825
  */
819
826
  export async function disconnectClaustrumEnrollment(paths, proposedName) {
820
- await ensurePrivateDirectory(dirname(paths.statePath));
827
+ await ensureClaustrumPrivateDirectory(dirname(paths.statePath));
821
828
  const lock = await acquireRefreshFileLock({
822
829
  // The same lock as the ceremony, so a token written by a concurrent
823
830
  // reconcile() can never land after this removes the files.
@@ -12,12 +12,13 @@
12
12
  // never replaces a view another process committed after this hub listed.
13
13
  import { createHash } from 'node:crypto';
14
14
  import { readdir, stat } from 'node:fs/promises';
15
- import { join } from 'node:path';
15
+ import { dirname, join } from 'node:path';
16
16
  import { createLogger } from '../logger/index.js';
17
17
  import { combineAbortSignals } from '../util/any-signal.js';
18
18
  import { ClaustrumUnreachableError } from './availability.js';
19
19
  import { createHubMember, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
20
20
  import { ClaustrumScopedCustody, } from './custody.js';
21
+ import { ensureClaustrumPrivateDirectory } from './enrollment.js';
21
22
  import { ClaustrumConsumerError } from './errors.js';
22
23
  import { DEFAULT_ROUTE_PREFIX, decodedVaultRoster, forgetPendingVaultDiscovery, isVaultRosterLockRefusal, readVaultRoster, refreshVaultRoster, vaultRosterSeed, } from './roster.js';
23
24
  import { drainShutdown, shutdownWarning } from './shutdown.js';
@@ -585,10 +586,11 @@ export class ClaustrumDiscoveryHub {
585
586
  }
586
587
  /**
587
588
  * Read each member's base view, list once, then commit each member's share
588
- * of the listing to its roster, push it into the member, and retain the
589
- * union. Each publication step checks first that the generation it started
590
- * in is still current. A member that this list did not commit is marked
591
- * pending, so a later tick lists again.
589
+ * of the listing to its roster (all members at once, each under its own
590
+ * roster's locks), push it into the member, and retain the union. Each
591
+ * publication step checks first that the generation it started in is
592
+ * still current. A member that this list did not commit is marked pending,
593
+ * so a later tick lists again.
592
594
  */
593
595
  async #discover(run) {
594
596
  if (!(await this.#readAuthority()))
@@ -598,12 +600,17 @@ export class ClaustrumDiscoveryHub {
598
600
  run.generation = generation;
599
601
  if (!this.#live(generation))
600
602
  return undefined;
603
+ // Folders that could not be made owner-only fail every member's commit,
604
+ // as an unreadable base fails its member's: each is marked pending.
605
+ const folders = await this.#ensureRosterDirectories().then(() => undefined, (error) => error instanceof Error ? error : new Error(String(error)));
601
606
  // What each member's file held before the list. Another process may
602
607
  // commit while this list runs; the base-view rule then keeps its newer
603
- // roster rather than replacing it with this older listing.
604
- const bases = new Map();
605
- for (const entry of this.#members.values())
606
- bases.set(entry, await readVaultRoster(entry.path).then((file) => (file ? { file } : {}), (error) => error instanceof Error ? error : new Error(String(error))));
608
+ // roster rather than replacing it with this older listing. Each file is
609
+ // read on its own, so the reads run together.
610
+ const bases = new Map(await Promise.all([...this.#members.values()].map(async (entry) => [
611
+ entry,
612
+ await readVaultRoster(entry.path).then((file) => (file ? { file } : {}), (error) => error instanceof Error ? error : new Error(String(error))),
613
+ ])));
607
614
  if (!this.#live(generation))
608
615
  return undefined;
609
616
  let inventory;
@@ -619,43 +626,28 @@ export class ClaustrumDiscoveryHub {
619
626
  this.#markPending(entry);
620
627
  throw error;
621
628
  }
629
+ if (!this.#live(generation))
630
+ return undefined;
631
+ // Every member's commit starts at once and none waits for another: each
632
+ // touches only its own roster file and takes only that file's locks (its
633
+ // discovery lease, then its write lock, as `refreshVaultRoster` always
634
+ // does), so no commit ever holds two members' locks and no order between
635
+ // members is needed. The results are then published in member order.
636
+ const members = this.#open();
637
+ const commits = await Promise.all(members.map((entry) => entry.hooks && !entry.closed
638
+ ? this.#commit(entry, entry.hooks, inventory, folders ?? bases.get(entry), generation)
639
+ : undefined));
640
+ if (!this.#live(generation))
641
+ return undefined;
622
642
  const errors = new Map();
623
643
  let complete = true;
624
- for (const entry of this.#open()) {
625
- if (!this.#live(generation))
626
- return undefined;
644
+ for (const [index, entry] of members.entries()) {
627
645
  const hooks = entry.hooks;
628
- if (!hooks || entry.closed)
646
+ const commit = commits[index];
647
+ if (!hooks || !commit)
629
648
  continue;
630
- const share = {
631
- ...inventory,
632
- credentials: inventory.credentials.filter((credential) => credential.member === entry.provider),
633
- skipped: inventory.skipped.filter((record) => record.member === entry.provider),
634
- };
635
- const base = bases.get(entry);
636
- let roster;
637
- try {
638
- if (!base)
639
- throw closed('Claustrum hub member has no base view');
640
- if (base instanceof Error)
641
- throw base;
642
- // A member's first roster under this key carries the declines and
643
- // order of its newest roster under an older key.
644
- const seed = base.file ? undefined : await this.#seed(entry);
645
- roster = await refreshVaultRoster({
646
- path: entry.path,
647
- custody: { discover: async () => share },
648
- // Generation g's commit checks that g is still current, not only
649
- // that vault mode is on, so off-then-on cannot let it into g+1.
650
- isActive: () => this.#live(generation) && this.#active === true,
651
- signal: generation.controller.signal,
652
- projection: () => ({ ...hooks.projection(), ...(seed && { seed }) }),
653
- listedOver: { view: base.file?.view },
654
- });
655
- }
656
- catch (error) {
657
- if (!this.#live(generation))
658
- return undefined;
649
+ if ('error' in commit) {
650
+ const { error } = commit;
659
651
  complete = false;
660
652
  this.#markPending(entry);
661
653
  // Another writer holding or taking this roster's locks is not this
@@ -668,6 +660,7 @@ export class ClaustrumDiscoveryHub {
668
660
  errors.set(entry.provider, error);
669
661
  continue;
670
662
  }
663
+ const { roster } = commit;
671
664
  if (!this.#live(generation))
672
665
  return undefined;
673
666
  // Not this list's roster: vault mode went off, the file was removed
@@ -707,6 +700,57 @@ export class ClaustrumDiscoveryHub {
707
700
  this.#discoveredAt = (this.#options.now ?? Date.now)();
708
701
  return { errors };
709
702
  }
703
+ /**
704
+ * Commit one member's share of `inventory` to its roster file over the
705
+ * base view read before the list. Every failure is returned, not thrown,
706
+ * so one member's failure leaves the other members' commits running.
707
+ */
708
+ async #commit(entry, hooks, inventory, base, generation) {
709
+ const share = {
710
+ ...inventory,
711
+ credentials: inventory.credentials.filter((credential) => credential.member === entry.provider),
712
+ skipped: inventory.skipped.filter((record) => record.member === entry.provider),
713
+ };
714
+ try {
715
+ if (!base)
716
+ throw closed('Claustrum hub member has no base view');
717
+ if (base instanceof Error)
718
+ throw base;
719
+ // A member's first roster under this key carries the declines and
720
+ // order of its newest roster under an older key.
721
+ const seed = base.file ? undefined : await this.#seed(entry);
722
+ const roster = await refreshVaultRoster({
723
+ path: entry.path,
724
+ custody: { discover: async () => share },
725
+ // Generation g's commit checks that g is still current, not only
726
+ // that vault mode is on, so off-then-on cannot let it into g+1.
727
+ isActive: () => this.#live(generation) && this.#active === true,
728
+ signal: generation.controller.signal,
729
+ projection: () => ({ ...hooks.projection(), ...(seed && { seed }) }),
730
+ listedOver: { view: base.file?.view },
731
+ });
732
+ return { roster };
733
+ }
734
+ catch (error) {
735
+ return { error };
736
+ }
737
+ }
738
+ /**
739
+ * Create the roster folders under the state folder (`rosters`, this host
740
+ * generation and this key) owner-only, as every other Claustrum private
741
+ * folder is: 0700 on POSIX, tightening a folder an earlier release left
742
+ * open, and private-files on Windows. Each is handled on its own so an
743
+ * existing open parent is tightened too. Without this, the first roster
744
+ * lock would create them with the process umask, usually 0755.
745
+ */
746
+ async #ensureRosterDirectories() {
747
+ for (const directory of [
748
+ dirname(this.#generationDirectory),
749
+ this.#generationDirectory,
750
+ join(this.#generationDirectory, this.#key),
751
+ ])
752
+ await ensureClaustrumPrivateDirectory(directory, {}, 'roster directory');
753
+ }
710
754
  /**
711
755
  * The preferences a member's first roster under this key starts from: the
712
756
  * declines and order of the newest roster of the same host generation and
@@ -1,4 +1,17 @@
1
1
  export declare function isLostMarkerRaceError(error: unknown): boolean;
2
+ /** Test-only fault injection between marker mkdir and owner.json write. */
3
+ export interface EvictionMarkerTestHooks {
4
+ /** Runs after the exclusive mkdir (and identity capture) before owner write. */
5
+ beforeOwnerWrite?: (evictPath: string, ownerPath: string) => Promise<void> | void;
6
+ /** Throw to fail the owner write; return an error to throw it. */
7
+ failOwnerWrite?: (evictPath: string, ownerPath: string) => Promise<unknown> | unknown;
8
+ }
9
+ /**
10
+ * Tests only: inject a failure or a directory replacement between the
11
+ * eviction-marker mkdir and its owner.json write. Production never sets this.
12
+ * Not exported from the fs entry point, so it is not part of the public API.
13
+ */
14
+ export declare function setEvictionMarkerTestHooksForTest(hooks?: EvictionMarkerTestHooks): void;
2
15
  export interface LockLoss {
3
16
  readonly reason: 'taken-over' | 'expired' | 'unreadable' | 'renewal-failed' | 'marker-lost';
4
17
  readonly expectedOwnerId: string;
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { mkdir, open, readFile, rename, rm, stat } from 'node:fs/promises';
2
+ import { lstat, mkdir, open, readFile, rename, rm, stat, } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
5
5
  import { LockOwnershipError, lockPathFor } from './with-lock.js';
@@ -13,9 +13,35 @@ import { LockOwnershipError, lockPathFor } from './with-lock.js';
13
13
  */
14
14
  async function createExclusiveText(path, text) {
15
15
  const handle = await open(path, 'wx', 0o600);
16
+ let createdStat;
17
+ try {
18
+ createdStat = await handle.stat();
19
+ }
20
+ catch {
21
+ createdStat = undefined;
22
+ }
16
23
  try {
17
24
  await handle.writeFile(text, 'utf8');
18
25
  }
26
+ catch (error) {
27
+ // A failed write after an exclusive create leaves a partial file behind.
28
+ // Remove only the file just created: when a contender has meanwhile
29
+ // replaced the path, the identities differ and the successor is left
30
+ // alone. Removal failures must never mask the original write error.
31
+ try {
32
+ const current = await lstat(path).catch(() => undefined);
33
+ if (createdStat &&
34
+ current &&
35
+ current.dev === createdStat.dev &&
36
+ current.ino === createdStat.ino) {
37
+ await rm(path, { force: true }).catch(() => { });
38
+ }
39
+ }
40
+ catch {
41
+ // Best effort only; the original error below explains the failure.
42
+ }
43
+ throw error;
44
+ }
19
45
  finally {
20
46
  await handle.close();
21
47
  }
@@ -31,6 +57,31 @@ export function isLostMarkerRaceError(error) {
31
57
  return (code === 'ENOENT' ||
32
58
  (!windowsPrivateFiles && (code === 'EINVAL' || code === 'ENOTDIR')));
33
59
  }
60
+ let evictionMarkerTestHooks;
61
+ /**
62
+ * Tests only: inject a failure or a directory replacement between the
63
+ * eviction-marker mkdir and its owner.json write. Production never sets this.
64
+ * Not exported from the fs entry point, so it is not part of the public API.
65
+ */
66
+ export function setEvictionMarkerTestHooksForTest(hooks) {
67
+ evictionMarkerTestHooks = hooks;
68
+ }
69
+ function sameMarkerDirectory(created, current) {
70
+ if (created.dev !== current.dev || created.ino !== current.ino)
71
+ return false;
72
+ // Windows reports the directory identity as a file id that can be 0; fall
73
+ // back to creation time so a reused id does not look like the same directory.
74
+ if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
75
+ return false;
76
+ return true;
77
+ }
78
+ /**
79
+ * An ownerless marker older than this is recoverable without waiting for the
80
+ * full eviction TTL. Honest holders write owner.json within tens of
81
+ * milliseconds of the mkdir, so one second leaves wide margin for slow Windows
82
+ * filesystems while still bounding the stall from a crashed holder.
83
+ */
84
+ const OWNERLESS_MARKER_GRACE_MS = 1_000;
34
85
  /** Filesystem leases share wall time across all callers and processes. */
35
86
  export function acquireRefreshFileLock(options) {
36
87
  return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
@@ -321,12 +372,66 @@ export async function acquireRefreshFileLockWithClock(options) {
321
372
  await removeLeaseObject(evictPath);
322
373
  }
323
374
  }
375
+ // Returns whether the directory at the marker path was still the one this
376
+ // process created when its owner write failed. Only then is the failure ours
377
+ // to report: a gone or replaced directory is a lost race.
378
+ async function removeOwnMarkerAfterFailedOwnerWrite(created) {
379
+ // Best effort only: never throws, so the original owner-write error below
380
+ // keeps explaining the failure. Removes the directory this process just
381
+ // created when its owner write failed, and leaves a contender's
382
+ // replacement alone when the identities differ.
383
+ if (!created)
384
+ return false;
385
+ let current;
386
+ try {
387
+ const st = await lstat(evictPath);
388
+ current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
389
+ }
390
+ catch {
391
+ // Renamed away by a contender's steal: nothing of ours left to clean.
392
+ return false;
393
+ }
394
+ if (!sameMarkerDirectory(created, current))
395
+ return false;
396
+ // Remove only an ownerless directory. An owner file that appeared after
397
+ // our failed write belongs to someone: ours goes through
398
+ // releaseEvictionMarker in the caller, and a contender's must stay, since
399
+ // it may be holding the marker right now.
400
+ try {
401
+ await stat(evictOwnerPath);
402
+ return true;
403
+ }
404
+ catch (error) {
405
+ if (error.code !== 'ENOENT')
406
+ return true;
407
+ }
408
+ try {
409
+ await removeLeaseObject(evictPath);
410
+ }
411
+ catch {
412
+ // A removal failure keeps the stale marker recoverable later; it must
413
+ // never mask the original owner-write error.
414
+ }
415
+ return true;
416
+ }
324
417
  async function tryAcquireEvictionMarker() {
325
418
  if (windowsPrivateFiles)
326
419
  await createPrivateDirectoryExclusive(evictPath);
327
420
  else
328
421
  await mkdir(evictPath);
422
+ let created;
329
423
  try {
424
+ const st = await lstat(evictPath);
425
+ created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
426
+ }
427
+ catch {
428
+ created = undefined;
429
+ }
430
+ try {
431
+ await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
432
+ const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
433
+ if (injected !== undefined)
434
+ throw injected;
330
435
  const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}\n`;
331
436
  if (windowsPrivateFiles)
332
437
  await createPrivateBytes(evictOwnerPath, bytes);
@@ -339,9 +444,26 @@ export async function acquireRefreshFileLockWithClock(options) {
339
444
  // path below does exactly that). That is a lost race, not a failure, so
340
445
  // report it as such and let the caller back off and retry rather than
341
446
  // failing the whole lock acquisition.
342
- if (isLostMarkerRaceError(error))
447
+ //
448
+ // The race codes alone cannot prove the directory is gone: the same
449
+ // codes can surface while our directory is still in place (for example
450
+ // a permission failure while writing the owner file, which used to
451
+ // leave an ownerless marker behind). The identity fence
452
+ // above removes only the directory this process created, and is a no-op
453
+ // when the contender renamed it away or replaced it, so run it on both
454
+ // branches before deciding between a retry and a failure.
455
+ // A race code while our own directory is still in place is not a lost
456
+ // race but a write that fails here every time: report it, rather than
457
+ // retrying the same failure until a deadline hides the cause.
458
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
459
+ if (isLostMarkerRaceError(error) && !stillOurs)
343
460
  return false;
344
- await releaseEvictionMarker();
461
+ try {
462
+ await releaseEvictionMarker();
463
+ }
464
+ catch {
465
+ // Removal must never mask the original owner-write error.
466
+ }
345
467
  throw error;
346
468
  }
347
469
  if (options.onStep)
@@ -358,10 +480,42 @@ export async function acquireRefreshFileLockWithClock(options) {
358
480
  return 'missing';
359
481
  throw error;
360
482
  }
361
- if (windowsPrivateFiles)
362
- await verifyPrivate(evictPath, 'directory', true);
363
- if (evictStat.mtimeMs + EVICT_TTL > now())
364
- return 'fresh';
483
+ if (windowsPrivateFiles) {
484
+ try {
485
+ await verifyPrivate(evictPath, 'directory', true);
486
+ }
487
+ catch (error) {
488
+ // The marker's holder can remove it between the stat above and this
489
+ // check. Absence means the marker is free, as when the stat finds
490
+ // nothing; every other refusal still escapes.
491
+ if (error.code === 'ENOENT')
492
+ return 'missing';
493
+ throw error;
494
+ }
495
+ }
496
+ if (evictStat.mtimeMs + EVICT_TTL > now()) {
497
+ // A fresh marker with no owner is either this process's orphan (its
498
+ // owner write just failed) or a holder that crashed between mkdir and
499
+ // owner write. Honest holders publish owner.json within tens of
500
+ // milliseconds, so recover ownerless markers after a short grace instead
501
+ // of stalling for the full TTL. Stealing one is safe: a live holder
502
+ // stalled past the grace sees its pending owner write fail with ENOENT
503
+ // (a lost race) and retries, rather than acting on a stolen marker.
504
+ let hasOwner = true;
505
+ try {
506
+ await stat(evictOwnerPath);
507
+ }
508
+ catch (error) {
509
+ if (error.code === 'ENOENT')
510
+ hasOwner = false;
511
+ else
512
+ return 'fresh';
513
+ }
514
+ if (hasOwner)
515
+ return 'fresh';
516
+ if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
517
+ return 'fresh';
518
+ }
365
519
  if (options.onStep)
366
520
  await options.onStep('stale-marker-stat');
367
521
  const claimedPath = `${evictPath}.${randomUUID()}`;
@@ -386,11 +540,13 @@ export async function acquireRefreshFileLockWithClock(options) {
386
540
  catch (error) {
387
541
  if (error.code === 'EEXIST') {
388
542
  if (windowsPrivateFiles) {
389
- await verifyPrivate(evictPath, 'directory', true);
390
543
  try {
544
+ await verifyPrivate(evictPath, 'directory', true);
391
545
  await readPrivateText(evictOwnerPath, true);
392
546
  }
393
547
  catch (ownerError) {
548
+ // A marker removed by its holder after the failed create is free:
549
+ // report it as unavailable for now so the caller retries.
394
550
  if (ownerError.code !== 'ENOENT')
395
551
  throw ownerError;
396
552
  }
@@ -686,7 +842,12 @@ export async function acquireRefreshFileLockWithClock(options) {
686
842
  released = true;
687
843
  cancelRenewalTimer();
688
844
  await renewalInFlight;
689
- for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
845
+ // A fresh marker may outlive a few quick retries, especially on Windows.
846
+ // Allow its full TTL plus recovery time, using a monotonic deadline so
847
+ // wall-clock adjustments cannot extend the retry deadline.
848
+ const deadline = performance.now() + EVICT_TTL + 1_000;
849
+ let delayMs = 5;
850
+ for (;;) {
690
851
  try {
691
852
  let removalConfirmed = false;
692
853
  const markerAcquired = await withEvictionMarker(async () => {
@@ -728,7 +889,11 @@ export async function acquireRefreshFileLockWithClock(options) {
728
889
  throw error;
729
890
  return;
730
891
  }
731
- await backoff();
892
+ const remainingMs = deadline - performance.now();
893
+ if (remainingMs <= 0)
894
+ break;
895
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remainingMs)));
896
+ delayMs = Math.min(delayMs * 2, 50);
732
897
  }
733
898
  // Do not delete by pathname without the marker: bounded retries leave the
734
899
  // lease to expire rather than risking removal of a successor's lock.
@@ -75,6 +75,16 @@ async function acquire(path, stale) {
75
75
  await remove(path);
76
76
  return acquire(path, 0);
77
77
  }
78
+ // The exclusive mkdir above succeeded: capture this directory's identity
79
+ // before any further step, so cleanup below removes only what we created.
80
+ let created;
81
+ try {
82
+ const st = await stat(path);
83
+ created = { dev: st.dev, ino: st.ino };
84
+ }
85
+ catch {
86
+ created = undefined;
87
+ }
78
88
  try {
79
89
  if (!precision) {
80
90
  const probe = new Date(Math.ceil(Date.now() / 1_000) * 1_000 + 5);
@@ -86,7 +96,22 @@ async function acquire(path, stale) {
86
96
  return { dev: observed.dev, ino: observed.ino, mtime };
87
97
  }
88
98
  catch (error) {
89
- await remove(path).catch(() => { });
99
+ // Only remove the directory this call created. A contender can rename it
100
+ // away and publish its own lock between the mkdir above and this failure;
101
+ // an unfenced rmdir would then delete the successor. The directory holds
102
+ // no owner file (mtime is the lease), so identity alone is the fence.
103
+ try {
104
+ if (created) {
105
+ const current = await stat(path).catch(() => undefined);
106
+ if (current &&
107
+ current.dev === created.dev &&
108
+ current.ino === created.ino)
109
+ await remove(path).catch(() => { });
110
+ }
111
+ }
112
+ catch {
113
+ // Best effort only; the original error below explains the failure.
114
+ }
90
115
  throw error;
91
116
  }
92
117
  }
@@ -5,57 +5,12 @@ import { recordSetupEnrollment, setupEnrollmentLine } from './command-error.js';
5
5
  import { defaultCommandRunner } from './command-runner.js';
6
6
  import { detectHosts } from './detect.js';
7
7
  import { connectSetupHost, HostNotEnrolledError } from './enroll.js';
8
+ import { parseSetupFlags, UNAVAILABLE_HOST_MESSAGE } from './flags.js';
8
9
  import { setupPaths } from './paths.js';
9
10
  import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
10
11
  import { selectSetupHosts } from './prompts.js';
11
12
  import { planOpenCodeRegistration, registerOpenCode, registerPi, } from './register.js';
12
13
  export const AMBIGUOUS_OPENCODE_MESSAGE = 'Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.';
13
- const UNAVAILABLE_HOST_MESSAGE = 'Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.';
14
- function flags(argv) {
15
- const result = {
16
- yes: false,
17
- dryRun: false,
18
- claustrum: false,
19
- noClaustrum: false,
20
- login: false,
21
- enrollOnly: false,
22
- hosts: [],
23
- opencode: undefined,
24
- };
25
- for (const arg of argv) {
26
- if (arg === '--yes')
27
- result.yes = true;
28
- else if (arg === '--dry-run')
29
- result.dryRun = true;
30
- else if (arg === '--claustrum')
31
- result.claustrum = true;
32
- else if (arg === '--no-claustrum')
33
- result.noClaustrum = true;
34
- else if (arg === '--login')
35
- result.login = true;
36
- else if (arg === '--enroll-only')
37
- result.enrollOnly = true;
38
- else if (arg.startsWith('--host=')) {
39
- const host = arg.slice('--host='.length);
40
- if (host !== 'opencode' && host !== 'pi')
41
- throw new Error(UNAVAILABLE_HOST_MESSAGE);
42
- result.hosts.push(host);
43
- }
44
- else if (/^--opencode=(1|2|both)$/.test(arg))
45
- result.opencode = arg.slice('--opencode='.length);
46
- else
47
- throw new Error(`Unknown setup argument: ${arg}`);
48
- }
49
- if (result.claustrum && result.noClaustrum)
50
- throw new Error('--claustrum and --no-claustrum cannot be used together.');
51
- if (result.login && result.claustrum)
52
- throw new Error('--login and --claustrum cannot be used together.');
53
- if (result.enrollOnly && result.login)
54
- throw new Error('--enroll-only and --login cannot be used together.');
55
- if (result.enrollOnly && result.noClaustrum)
56
- throw new Error('--enroll-only and --no-claustrum cannot be used together.');
57
- return result;
58
- }
59
14
  function validatePlugin(plugin) {
60
15
  for (const pkg of Object.values(plugin.packages)) {
61
16
  if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(pkg))
@@ -92,7 +47,7 @@ async function enrollmentReport(plugin, hosts, recorded) {
92
47
  return report;
93
48
  }
94
49
  export async function runSetup(plugin, argv = [], io = {}) {
95
- const options = flags(argv);
50
+ const options = parseSetupFlags(argv);
96
51
  validatePlugin(plugin);
97
52
  const terminal = io.terminal ?? processTerminal();
98
53
  const detection = await detectHosts(plugin, io);
@@ -234,7 +189,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
234
189
  printLine(terminal, `${write.changed ? 'Would write' : 'Unchanged'} ${write.path}:\n${write.content}`);
235
190
  if (!options.enrollOnly && hosts.includes('pi'))
236
191
  printLine(terminal, `Would run ${detection.pi.executable} install npm:${plugin.packages.pi}@${plugin.version}`);
237
- if (!options.enrollOnly)
192
+ if (!options.enrollOnly && plugin.migrate)
238
193
  for (const host of hosts)
239
194
  printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
240
195
  }
@@ -277,7 +232,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
277
232
  else
278
233
  await registerPi(plugin, detection.pi.executable, io);
279
234
  await stopped();
280
- await plugin.migrate(host, context);
235
+ await plugin.migrate?.(host, context);
281
236
  }
282
237
  }
283
238
  catch (error) {
@@ -0,0 +1,50 @@
1
+ import type { OpenCodeGeneration, SetupHost } from './types.js';
2
+ export declare const UNAVAILABLE_HOST_MESSAGE = "Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.";
3
+ type SwitchKey = 'yes' | 'dryRun' | 'claustrum' | 'noClaustrum' | 'login' | 'enrollOnly';
4
+ /**
5
+ * One flag the shared setup parser accepts. A switch sets `key` to true; a
6
+ * value flag takes one of `values` as `--name=value`, and also as the next
7
+ * argument (`--name value`) when `spaceForm` is set. `invalid` replaces the
8
+ * unknown-argument refusal when a value flag gets a value it does not accept.
9
+ */
10
+ export type SetupFlag = {
11
+ name: string;
12
+ key: SwitchKey;
13
+ description: string;
14
+ } | {
15
+ name: string;
16
+ key: 'hosts' | 'opencode';
17
+ values: readonly string[];
18
+ spaceForm?: boolean;
19
+ invalid?: string;
20
+ description: string;
21
+ };
22
+ /**
23
+ * Every flag `runSetup` accepts. The parser and `setupUsage` both read this
24
+ * table, so the help a plugin prints cannot list a flag the parser refuses or
25
+ * leave out one it accepts.
26
+ */
27
+ export declare const SETUP_FLAGS: readonly SetupFlag[];
28
+ export interface SetupFlags {
29
+ yes: boolean;
30
+ dryRun: boolean;
31
+ claustrum: boolean;
32
+ noClaustrum: boolean;
33
+ login: boolean;
34
+ enrollOnly: boolean;
35
+ hosts: SetupHost[];
36
+ opencode: OpenCodeGeneration | undefined;
37
+ }
38
+ /** Parse setup's arguments against `SETUP_FLAGS`, refusing anything else. */
39
+ export declare function parseSetupFlags(argv: readonly string[]): SetupFlags;
40
+ /**
41
+ * The flags `runSetup` accepts, one per line, for a plugin's `setup --help`.
42
+ * The shared parser has no `--help` of its own: the plugin's bin checks for
43
+ * `--help` or `-h` before calling `runSetup`, prints this text and any lines of
44
+ * its own, and exits 0. With `command` the text starts with a usage line, such
45
+ * as `Usage: example-auth setup [flags]`.
46
+ */
47
+ export declare function setupUsage(options?: {
48
+ command?: string;
49
+ }): string;
50
+ export {};
@@ -0,0 +1,123 @@
1
+ export const UNAVAILABLE_HOST_MESSAGE = 'Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.';
2
+ /**
3
+ * Every flag `runSetup` accepts. The parser and `setupUsage` both read this
4
+ * table, so the help a plugin prints cannot list a flag the parser refuses or
5
+ * leave out one it accepts.
6
+ */
7
+ export const SETUP_FLAGS = [
8
+ {
9
+ name: '--yes',
10
+ key: 'yes',
11
+ description: 'Run without questions and set up every found host. Does not choose the vault.',
12
+ },
13
+ {
14
+ name: '--dry-run',
15
+ key: 'dryRun',
16
+ description: 'Print what setup would do without changing anything.',
17
+ },
18
+ {
19
+ name: '--host',
20
+ key: 'hosts',
21
+ values: ['opencode', 'pi'],
22
+ spaceForm: true,
23
+ invalid: UNAVAILABLE_HOST_MESSAGE,
24
+ description: 'Set up only this host; repeat the flag for both. Also written --host=<host>.',
25
+ },
26
+ {
27
+ name: '--opencode',
28
+ key: 'opencode',
29
+ values: ['1', '2', 'both'],
30
+ description: 'Register for this OpenCode generation.',
31
+ },
32
+ {
33
+ name: '--claustrum',
34
+ key: 'claustrum',
35
+ description: 'Connect the hosts to the Claustrum vault.',
36
+ },
37
+ {
38
+ name: '--no-claustrum',
39
+ key: 'noClaustrum',
40
+ description: 'Do not offer the Claustrum vault; sign in locally.',
41
+ },
42
+ {
43
+ name: '--login',
44
+ key: 'login',
45
+ description: 'Sign in locally instead of using the Claustrum vault.',
46
+ },
47
+ {
48
+ name: '--enroll-only',
49
+ key: 'enrollOnly',
50
+ description: 'Only connect the hosts to the Claustrum vault; register nothing and migrate nothing.',
51
+ },
52
+ ];
53
+ function unknownArgument(arg) {
54
+ return new Error(`Unknown setup argument: ${arg}. Run the plugin's own setup --help to list the flags setup accepts.`);
55
+ }
56
+ /** Parse setup's arguments against `SETUP_FLAGS`, refusing anything else. */
57
+ export function parseSetupFlags(argv) {
58
+ const result = {
59
+ yes: false,
60
+ dryRun: false,
61
+ claustrum: false,
62
+ noClaustrum: false,
63
+ login: false,
64
+ enrollOnly: false,
65
+ hosts: [],
66
+ opencode: undefined,
67
+ };
68
+ for (let index = 0; index < argv.length; index++) {
69
+ const arg = argv[index];
70
+ const equals = arg.indexOf('=');
71
+ const name = equals === -1 ? arg : arg.slice(0, equals);
72
+ const flag = SETUP_FLAGS.find((entry) => entry.name === name);
73
+ if (!flag)
74
+ throw unknownArgument(arg);
75
+ if (!('values' in flag)) {
76
+ if (equals !== -1)
77
+ throw unknownArgument(arg);
78
+ result[flag.key] = true;
79
+ continue;
80
+ }
81
+ let value;
82
+ if (equals !== -1)
83
+ value = arg.slice(equals + 1);
84
+ else if (flag.spaceForm)
85
+ value = argv[++index];
86
+ else
87
+ throw unknownArgument(arg);
88
+ if (value === undefined || !flag.values.includes(value))
89
+ throw flag.invalid ? new Error(flag.invalid) : unknownArgument(arg);
90
+ if (flag.key === 'hosts')
91
+ result.hosts.push(value);
92
+ else
93
+ result.opencode = value;
94
+ }
95
+ if (result.claustrum && result.noClaustrum)
96
+ throw new Error('--claustrum and --no-claustrum cannot be used together.');
97
+ if (result.login && result.claustrum)
98
+ throw new Error('--login and --claustrum cannot be used together.');
99
+ if (result.enrollOnly && result.login)
100
+ throw new Error('--enroll-only and --login cannot be used together.');
101
+ if (result.enrollOnly && result.noClaustrum)
102
+ throw new Error('--enroll-only and --no-claustrum cannot be used together.');
103
+ return result;
104
+ }
105
+ /**
106
+ * The flags `runSetup` accepts, one per line, for a plugin's `setup --help`.
107
+ * The shared parser has no `--help` of its own: the plugin's bin checks for
108
+ * `--help` or `-h` before calling `runSetup`, prints this text and any lines of
109
+ * its own, and exits 0. With `command` the text starts with a usage line, such
110
+ * as `Usage: example-auth setup [flags]`.
111
+ */
112
+ export function setupUsage(options = {}) {
113
+ const labels = SETUP_FLAGS.map((flag) => 'values' in flag
114
+ ? `${flag.name}${flag.spaceForm ? ' ' : '='}${flag.values.join('|')}`
115
+ : flag.name);
116
+ const width = Math.max(...labels.map((label) => label.length));
117
+ const lines = SETUP_FLAGS.map((flag, index) => ` ${labels[index].padEnd(width)} ${flag.description}`);
118
+ return [
119
+ ...(options.command ? [`Usage: ${options.command} [flags]`, ''] : []),
120
+ 'Flags:',
121
+ ...lines,
122
+ ].join('\n');
123
+ }
@@ -2,6 +2,7 @@ export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
2
  export { SetupCommandError, setupEnrollment } from './command-error.js';
3
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
4
4
  export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, type HostNotEnrolledReason, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
5
+ export { setupUsage } from './flags.js';
5
6
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
6
7
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
7
8
  export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -2,5 +2,6 @@ export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
2
  export { SetupCommandError, setupEnrollment } from './command-error.js';
3
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
4
4
  export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
5
+ export { setupUsage } from './flags.js';
5
6
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
7
  export { planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
@@ -61,7 +61,13 @@ export interface SetupPlugin {
61
61
  */
62
62
  beforeSignIn?(host: SetupHost, context: SetupCallbackContext): Promise<void>;
63
63
  signInLocal(host: SetupHost, context: SetupCallbackContext): Promise<void>;
64
- migrate(host: SetupHost, context: SetupCallbackContext): Promise<void>;
64
+ /**
65
+ * Moves the host's existing provider credentials into place after the host
66
+ * is registered. Optional: a plugin with nothing to migrate (one that only
67
+ * reads credentials from the vault) leaves it out, and setup then neither
68
+ * calls it nor mentions migration in its dry-run plan.
69
+ */
70
+ migrate?(host: SetupHost, context: SetupCallbackContext): Promise<void>;
65
71
  /** Reject mixed local/vault credentials and activate provider-specific vault access before registration. */
66
72
  beforeRegister?(host: SetupHost, mode: 'local' | 'claustrum', context: SetupCallbackContext): Promise<void>;
67
73
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.27.1",
3
+ "version": "0.29.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": {
@@ -111,7 +111,7 @@
111
111
  "check:opentui-0511": "bun scripts/check-opentui-0511.mjs"
112
112
  },
113
113
  "dependencies": {
114
- "@cortexkit/private-files": "^0.2.1",
114
+ "@cortexkit/private-files": "^0.2.2",
115
115
  "jsonc-parser": "^3.3.1"
116
116
  },
117
117
  "peerDependencies": {