@cortexkit/common-auth 0.26.0 → 0.27.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.
@@ -3,14 +3,15 @@ import type { ClaustrumScopedClient } from './custody.js';
3
3
  export { ClaustrumCredentialError, type ClaustrumReporterSource, type EnrollmentTokenFile, } from '@cortexkit/claustrum-client';
4
4
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
5
5
  export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, type SendOptions, } from './consumer.js';
6
- export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, } from './custody.js';
6
+ export { type AccountIdentitySource, type ClassifyingClaustrumFamily, type ClaustrumFamily, type ClaustrumFamilyInput, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, type VaultRowFacts, } from './custody.js';
7
7
  export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
9
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
10
+ export { ClaustrumDiscoveryHub, type ClaustrumDiscoveryHubOptions, type ClaustrumHubMemberOptions, type ClaustrumHubRefusals, type ClaustrumLeasedCustody, type CustodyLease, } from './hub.js';
10
11
  export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaLookup, type InsulaQuotaMiss, type InsulaQuotaOptions, type InsulaQuotaReading, type InsulaQuotaResult, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } from './insula.js';
11
12
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
12
13
  export { drainVaultQuota } from './quota-writer.js';
13
- export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, type ReorderVaultRosterOptions, type ReorderVaultRosterResult, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
14
+ export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, type ReorderVaultRosterOptions, type ReorderVaultRosterResult, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, type VaultRosterSeed, vaultRosterSeed, vaultRoutingRows, } from './roster.js';
14
15
  export { type ChangeNotice, ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, type ScopedRosterWatchOptions, type ScopedWatchEnd, type ScopedWatchHandle, type ScopedWatchNoticeShape, type ScopedWatchSource, WATCH_RETRY_MS, type WatchMode, } from './watch.js';
15
16
  /**
16
17
  * Connect the client that lists and fetches this consumer's vault credentials
@@ -12,10 +12,11 @@ export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRo
12
12
  export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
13
13
  export { ClaustrumConsumerError, } from './errors.js';
14
14
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
15
+ export { ClaustrumDiscoveryHub, } from './hub.js';
15
16
  export { acquireInsulaQuotaSource, } from './insula.js';
16
17
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
17
18
  export { drainVaultQuota } from './quota-writer.js';
18
- export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
19
+ export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, vaultRosterSeed, vaultRoutingRows, } from './roster.js';
19
20
  export { ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, WATCH_RETRY_MS, } from './watch.js';
20
21
  /**
21
22
  * Connect the client that lists and fetches this consumer's vault credentials
@@ -62,7 +62,25 @@ export interface ProjectionOptions {
62
62
  routePrefix?: string;
63
63
  mapAccount?: AccountMapper;
64
64
  now?: number;
65
+ /**
66
+ * Preferences carried over from another roster file, used only when there
67
+ * is no previous roster: its declines become this roster's declines, and
68
+ * its account order sorts the rows this inventory produces. No row of the
69
+ * seed is ever projected, so a seed cannot make an account routable.
70
+ */
71
+ seed?: VaultRosterSeed;
72
+ }
73
+ /** The preferences one roster file can pass to a first projection elsewhere. */
74
+ export interface VaultRosterSeed {
75
+ readonly declined: readonly DeclinedAccount[];
76
+ /** Accounts in the seed roster's order, matched by account, then by id. */
77
+ readonly order: readonly {
78
+ readonly credentialId: string;
79
+ readonly accountIdentity?: string;
80
+ }[];
65
81
  }
82
+ /** Declines and account order of `roster`, and nothing else of it. */
83
+ export declare function vaultRosterSeed(roster: VaultRosterFile): VaultRosterSeed;
66
84
  export declare const DEFAULT_ROUTE_PREFIX = "vault:";
67
85
  /**
68
86
  * Project the vault's list onto the previous roster. Pure: callers serialize
@@ -87,6 +105,12 @@ export declare function projectVaultRoster(previous: VaultRosterFile | undefined
87
105
  * reaches admission.
88
106
  */
89
107
  export declare function vaultRoutingRows(roster: VaultRosterFile | undefined): RoutingRow[];
108
+ /**
109
+ * `roster` as `readVaultRoster` decodes it from the file that holds it, so a
110
+ * committed roster and a later read of its file compare equal. Package
111
+ * internal: not exported from `/claustrum`.
112
+ */
113
+ export declare function decodedVaultRoster(roster: VaultRosterFile): VaultRosterFile;
90
114
  export declare function readVaultRoster(path: string): Promise<VaultRosterFile | undefined>;
91
115
  /** The ownership assertion available to a roster mutation callback. */
92
116
  export interface VaultRosterLockContext {
@@ -190,6 +214,16 @@ export declare function applyVaultQuota(current: VaultRosterFile | undefined, in
190
214
  kept: boolean;
191
215
  };
192
216
  export declare function forgetPendingVaultDiscovery(path: string): void;
217
+ /**
218
+ * Whether `error` from a roster commit at `path` means another writer had the
219
+ * roster at that moment, not that the commit itself failed: the discovery
220
+ * lease was busy before any roster existed, the write lock stayed busy, or a
221
+ * lock this commit held was lost. On Windows the same lock steps can reject
222
+ * with a PrivateFileError instead (a lock file that could not be read or
223
+ * replaced while another process held it), so a PrivateFileError naming one
224
+ * of this roster's lock files counts the same on every OS.
225
+ */
226
+ export declare function isVaultRosterLockRefusal(path: string, error: unknown): boolean;
193
227
  /**
194
228
  * Discover and commit the roster. The lease covers the list call and the
195
229
  * commit, not just the write: an opaque view cannot tell a delayed old reply
@@ -206,6 +240,19 @@ export declare function refreshVaultRoster(options: {
206
240
  signal?: AbortSignal;
207
241
  projection?: ProjectionOptions | (() => ProjectionOptions);
208
242
  onInventory?: (inventory: VaultInventory) => void;
243
+ /**
244
+ * For a caller that listed before taking this path's discovery lease (the
245
+ * discovery hub lists once for several rosters): the view this roster file
246
+ * held before that list. `custody.discover` then returns that list. It is
247
+ * held to the rule a kept discovery is held to below: it is projected only
248
+ * while the file still holds this view or the list's own view. Otherwise
249
+ * another process committed since the list, and the file is returned
250
+ * unchanged. No discovery is kept for a later call, because such a caller
251
+ * lists again.
252
+ */
253
+ listedOver?: {
254
+ readonly view: string | undefined;
255
+ };
209
256
  }): Promise<VaultRosterFile | undefined>;
210
257
  /**
211
258
  * A host-owned main account as last verified from the vault: the plugin's
@@ -1,12 +1,35 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { resolve } from 'node:path';
3
- import { acquireRefreshFileLock, LockContentionError, withLock, writeJsonAtomic, } from '../fs/index.js';
3
+ import { acquireRefreshFileLock, LockContentionError, LockOwnershipError, lockPathFor, PrivateFileError, withLock, writeJsonAtomic, } from '../fs/index.js';
4
4
  import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
5
5
  import { decodeQuotaMap, isQuotaObservation, mergeQuotaObservation, } from '../quota/index.js';
6
6
  import { ClaustrumConsumerError } from './errors.js';
7
7
  import { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
8
8
  import { enqueueVaultQuota, pendingVaultQuota, } from './quota-writer.js';
9
9
  export { drainVaultQuota } from './quota-writer.js';
10
+ /** Declines and account order of `roster`, and nothing else of it. */
11
+ export function vaultRosterSeed(roster) {
12
+ return {
13
+ declined: roster.declined.map((entry) => ({ ...entry })),
14
+ order: roster.rows.flatMap((row) => memberIds(row).map((credentialId) => ({
15
+ credentialId,
16
+ ...(row.accountIdentity !== undefined && {
17
+ accountIdentity: row.accountIdentity,
18
+ }),
19
+ }))),
20
+ };
21
+ }
22
+ /** Where a projected row falls in the seed's order; unknown rows go last. */
23
+ function seedIndex(seed, row) {
24
+ const ids = memberIds(row);
25
+ const byAccount = row.accountIdentity === undefined
26
+ ? -1
27
+ : seed.order.findIndex((entry) => entry.accountIdentity === row.accountIdentity);
28
+ const index = byAccount >= 0
29
+ ? byAccount
30
+ : seed.order.findIndex((entry) => ids.includes(entry.credentialId));
31
+ return index >= 0 ? index : Infinity;
32
+ }
10
33
  export const DEFAULT_ROUTE_PREFIX = 'vault:';
11
34
  function hash(value) {
12
35
  return createHash('sha256').update(value).digest('hex');
@@ -47,8 +70,9 @@ export function projectVaultRoster(previous, inventory, options = {}) {
47
70
  const prefix = options.routePrefix ?? DEFAULT_ROUTE_PREFIX;
48
71
  const reserved = options.reservedRouteIds ?? new Set();
49
72
  const previousRows = previous?.rows ?? [];
73
+ const seed = previous ? undefined : options.seed;
50
74
  // Declines follow the account and outlive its records, so none is pruned.
51
- const declined = [...(previous?.declined ?? [])];
75
+ const declined = [...(previous?.declined ?? seed?.declined ?? [])];
52
76
  const complete = inventory.skipped.length === 0;
53
77
  const listed = new Set(inventory.credentials.map((credential) => credential.credentialId));
54
78
  const rejectedIds = new Set(inventory.skipped.flatMap((record) => record.credentialId === undefined ? [] : [record.credentialId]));
@@ -146,6 +170,11 @@ export function projectVaultRoster(previous, inventory, options = {}) {
146
170
  ...(!chosen.claimed && identity !== undefined && { unclaimed: true }),
147
171
  },
148
172
  });
173
+ // With no previous roster every row is new; a seed from another key
174
+ // sorts them by that key's order instead of by credential id.
175
+ const pushed = projected.at(-1);
176
+ if (seed && pushed)
177
+ pushed.previousIndex = seedIndex(seed, pushed.row);
149
178
  }
150
179
  // An account the reply does not account for keeps its last good projection:
151
180
  // a rejected record must not read as the account having been removed. A
@@ -293,6 +322,14 @@ function decodeRoster(value) {
293
322
  declined,
294
323
  };
295
324
  }
325
+ /**
326
+ * `roster` as `readVaultRoster` decodes it from the file that holds it, so a
327
+ * committed roster and a later read of its file compare equal. Package
328
+ * internal: not exported from `/claustrum`.
329
+ */
330
+ export function decodedVaultRoster(roster) {
331
+ return decodeRoster(JSON.parse(JSON.stringify(roster)));
332
+ }
296
333
  export async function readVaultRoster(path) {
297
334
  let text;
298
335
  try {
@@ -560,6 +597,33 @@ const pendingDiscoveries = new Map();
560
597
  export function forgetPendingVaultDiscovery(path) {
561
598
  pendingDiscoveries.delete(resolve(path));
562
599
  }
600
+ /**
601
+ * Whether `error` from a roster commit at `path` means another writer had the
602
+ * roster at that moment, not that the commit itself failed: the discovery
603
+ * lease was busy before any roster existed, the write lock stayed busy, or a
604
+ * lock this commit held was lost. On Windows the same lock steps can reject
605
+ * with a PrivateFileError instead (a lock file that could not be read or
606
+ * replaced while another process held it), so a PrivateFileError naming one
607
+ * of this roster's lock files counts the same on every OS.
608
+ */
609
+ export function isVaultRosterLockRefusal(path, error) {
610
+ const target = resolve(path);
611
+ if (error instanceof ClaustrumConsumerError)
612
+ return error.kind === 'roster-busy';
613
+ if (error instanceof LockContentionError ||
614
+ error instanceof LockOwnershipError)
615
+ return resolve(error.details.target) === target;
616
+ if (error instanceof PrivateFileError) {
617
+ const failed = resolve(error.path);
618
+ return [WRITE_LOCK.name, DISCOVERY_LEASE.name].some((name) => {
619
+ const lock = lockPathFor(target, name);
620
+ // The lock file itself, its eviction marker and the temporary files
621
+ // its owner record is staged in all start with the lock path.
622
+ return failed === lock || failed.startsWith(`${lock}.`);
623
+ });
624
+ }
625
+ return false;
626
+ }
563
627
  /**
564
628
  * Discover and commit the roster. The lease covers the list call and the
565
629
  * commit, not just the write: an opaque view cannot tell a delayed old reply
@@ -589,10 +653,11 @@ export async function refreshVaultRoster(options) {
589
653
  return persisted;
590
654
  }
591
655
  const key = resolve(options.path);
656
+ const listedOver = options.listedOver;
592
657
  let discovered;
593
658
  try {
594
659
  const previous = await readVaultRoster(options.path);
595
- const pending = pendingDiscoveries.get(key);
660
+ const pending = listedOver ? undefined : pendingDiscoveries.get(key);
596
661
  // Opaque view cursors cannot be ordered. Reuse a discovery only while no
597
662
  // peer has committed a different view since it was read.
598
663
  discovered =
@@ -613,6 +678,10 @@ export async function refreshVaultRoster(options) {
613
678
  return { result: undefined };
614
679
  options.signal?.throwIfAborted();
615
680
  await lease.assertOwned();
681
+ if (listedOver &&
682
+ current?.view !== listedOver.view &&
683
+ current?.view !== inventory.view)
684
+ return { result: current };
616
685
  const projection = typeof options.projection === 'function'
617
686
  ? options.projection()
618
687
  : options.projection;
@@ -620,6 +689,7 @@ export async function refreshVaultRoster(options) {
620
689
  const changed = JSON.stringify(current) !== JSON.stringify(next);
621
690
  return { ...(changed && { next }), result: next };
622
691
  }, {
692
+ signal: options.signal,
623
693
  beforePublish: async () => {
624
694
  options.signal?.throwIfAborted();
625
695
  await lease.assertOwned();
@@ -629,6 +699,7 @@ export async function refreshVaultRoster(options) {
629
699
  catch (error) {
630
700
  if (error instanceof LockContentionError &&
631
701
  discovered &&
702
+ !listedOver &&
632
703
  !options.signal?.aborted &&
633
704
  (await active()))
634
705
  pendingDiscoveries.set(key, discovered);
@@ -0,0 +1,8 @@
1
+ import type { ClaustrumLogger } from './errors.js';
2
+ /** Retired generations report separately until their owner closes and shares one warning. */
3
+ export declare function shutdownWarning(logger: Pick<ClaustrumLogger, 'warn'>, shutdown?: AbortSignal): (pendingOperations: number) => void;
4
+ /**
5
+ * Give cancelled background work two seconds to release its handles without letting
6
+ * an unresponsive connector or disk hold the host's shutdown indefinitely.
7
+ */
8
+ export declare function drainShutdown(pending: ReadonlySet<Promise<unknown>>, onTimeout: (pendingOperations: number) => void): Promise<void>;
@@ -0,0 +1,42 @@
1
+ /** Retired generations report separately until their owner closes and shares one warning. */
2
+ export function shutdownWarning(logger, shutdown) {
3
+ let warned = false;
4
+ return (pendingOperations) => {
5
+ if (warned)
6
+ return;
7
+ if (!shutdown || shutdown.aborted)
8
+ warned = true;
9
+ logger.warn('claustrum shutdown drain timed out', { pendingOperations });
10
+ };
11
+ }
12
+ /**
13
+ * Give cancelled background work two seconds to release its handles without letting
14
+ * an unresponsive connector or disk hold the host's shutdown indefinitely.
15
+ */
16
+ export async function drainShutdown(pending, onTimeout) {
17
+ if (!pending.size)
18
+ return;
19
+ let timer;
20
+ let expired = false;
21
+ const drained = (async () => {
22
+ while (!expired && pending.size)
23
+ await Promise.allSettled([...pending]);
24
+ })();
25
+ try {
26
+ await Promise.race([
27
+ drained,
28
+ new Promise((resolve) => {
29
+ timer = setTimeout(() => {
30
+ expired = true;
31
+ resolve();
32
+ }, 2_000);
33
+ }),
34
+ ]);
35
+ if (expired && pending.size)
36
+ onTimeout(pending.size);
37
+ }
38
+ finally {
39
+ expired = true;
40
+ clearTimeout(timer);
41
+ }
42
+ }
@@ -28,7 +28,7 @@ type RefreshFileLockOptions = {
28
28
  onContended?: () => void;
29
29
  /** Synchronous, never awaited; throws and returned promise/thenable rejections are isolated. */
30
30
  onRenewalTimer?: (event: 'scheduled' | 'cancelled') => void;
31
- onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
31
+ onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lease-contention-read-ready' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
32
32
  };
33
33
  /** Filesystem leases share wall time across all callers and processes. */
34
34
  export declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
@@ -178,19 +178,28 @@ export async function acquireRefreshFileLockWithClock(options) {
178
178
  }
179
179
  async function leaseContention(error) {
180
180
  const code = error.code;
181
- if (code === 'EEXIST') {
182
- if (windowsPrivateFiles)
183
- await readOwner();
184
- return true;
185
- }
186
- if (code === 'EISDIR') {
187
- if (windowsPrivateFiles) {
188
- await verifyPrivate(lockPath, 'directory', true);
189
- await readPrivateText(legacyOwnerPath, true);
181
+ if (code !== 'EEXIST' && code !== 'EISDIR')
182
+ return false;
183
+ if (windowsPrivateFiles) {
184
+ if (options.onStep)
185
+ await options.onStep('lease-contention-read-ready');
186
+ try {
187
+ if (code === 'EISDIR') {
188
+ await verifyPrivate(lockPath, 'directory', true);
189
+ await readPrivateText(legacyOwnerPath, true);
190
+ }
191
+ else
192
+ await readOwner();
193
+ }
194
+ catch (readError) {
195
+ // The holder can release after exclusive creation reports a collision.
196
+ // Only absence permits another acquisition attempt; security and sharing
197
+ // refusals must still escape rather than being treated as contention.
198
+ if (readError.code !== 'ENOENT')
199
+ throw readError;
190
200
  }
191
- return true;
192
201
  }
193
- return false;
202
+ return true;
194
203
  }
195
204
  async function tryAcquire() {
196
205
  if (windowsPrivateFiles)
@@ -8,8 +8,11 @@
8
8
  * - `host-credential-on-wire`: after every rewrite, a header still carried
9
9
  * one of the host's placeholder credentials. Sending it would leak a
10
10
  * non-routable value to the provider and fail with a confusing error.
11
+ * - `placement-refused`: an opt-in placeholder gate found the placeholder in
12
+ * multiple headers or outside the credential location it can serve. No
13
+ * account has been selected and no account headers have been read.
11
14
  */
12
- export type OpenCode2AuthFailureKind = 'no-account' | 'host-credential-on-wire';
15
+ export type OpenCode2AuthFailureKind = 'no-account' | 'host-credential-on-wire' | 'placement-refused';
13
16
  export declare class OpenCode2AuthError extends Error {
14
17
  readonly kind: OpenCode2AuthFailureKind;
15
18
  readonly providerID: string;
@@ -1,8 +1,8 @@
1
1
  export type { OpenCode2AuthFailureKind } from './errors.js';
2
2
  export { OpenCode2AuthError } from './errors.js';
3
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
3
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, } from './install.js';
4
4
  export type { FormAnswer, LoginContext, PoolAuthorization, PoolLoginMethod, RegisterOpenCode2AuthMethodsOptions, VaultActivationMethod, } from './integration.js';
5
5
  export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
6
6
  export type { ServerSentEvent } from './sse.js';
7
7
  export { watchServerSentEvents } from './sse.js';
8
- export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryReason, SelectingHook, Transport, } from './types.js';
8
+ export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, ChooseAccountResult, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryHold, RetryReason, SelectingHook, Transport, } from './types.js';
@@ -1,4 +1,4 @@
1
1
  export { OpenCode2AuthError } from './errors.js';
2
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
2
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, } from './install.js';
3
3
  export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
4
4
  export { watchServerSentEvents } from './sse.js';
@@ -1,5 +1,7 @@
1
- import type { HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
1
+ import type { ChooseAccountResult, HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
2
2
  export declare const DEFAULT_MAX_RECORDS = 512;
3
+ /** Bound adapter waits while allowing a 15-minute reset plus session jitter. */
4
+ export declare const MAX_RETRY_HOLD_MS: number;
3
5
  /**
4
6
  * The request header `model.request` sets to the attempt it started. The
5
7
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -49,8 +51,8 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
49
51
  * compares the host-prepared secret exactly, then selects a fresh attempt only
50
52
  * for an owned send. Request-object attribution therefore needs no attempt
51
53
  * header. Frames are owned by the latest handshake of their session and kind;
52
- * retry runs only when the session's latest transport was owned. The host's
53
- * retry hook has no request identity, so concurrent mixed-ownership calls
54
- * cannot be distinguished there; owned retries retain the heuristic above.
54
+ * retry runs only when the session's latest transport was owned and the session
55
+ * has never mixed owned and foreign transports. The host's retry hook has no
56
+ * request identity, so a mixed session must keep the host's retry decision.
55
57
  */
56
- export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;
58
+ export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A, ChooseAccountResult>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;