@cortexkit/common-auth 0.27.0 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,20 +7,4 @@ Shared libraries for the CortexKit auth plugins for OpenCode and Pi: openai-auth
7
7
  - [OpenCode 2 transport spike](research/opencode2-transport/REPORT.md): can a plugin own the transport on OpenCode 2?
8
8
  - [OpenCode 2 native-driver spike](research/opencode2-thin/REPORT.md): multi-account support through hooks on OpenCode 2's built-in OpenAI driver.
9
9
 
10
- ## Mutation catalogue
11
-
12
- A passing safety test proves little until it has been seen to fail. [`mutations.toml`](mutations.toml) is the checked-in catalogue: each row deliberately breaks one guard in `src/` (or a CI scan script) and names the Bun test that must fail because of it, so a guard cannot silently stop guarding. A row earns its place by guarding a silent, costly failure: lock exclusion, crash safety, credential loss or leakage, a single-use token used twice, misattributed quota, a wire contract, data loss. Style and cosmetics do not.
13
-
14
- The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/9d6b663dac487bb982c7bfd18a96eee2292164ad/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
15
-
16
- ```sh
17
- cargo install --locked --git https://github.com/cortexkit/commons --rev 9d6b663dac487bb982c7bfd18a96eee2292164ad cortexkit-mutate
18
- ckdev-mutate check --strict
19
- ckdev-mutate run --all
20
- ckdev-mutate run --diff origin/main
21
- ckdev-mutate run --only fs-lock-try-once-refuses-held-lock
22
- ```
23
-
24
- Every row must report CAUGHT. Replay with the Bun version CI pins (1.3.14): the row `rpc-declared-oversize-413-half-closes` guards the RPC server's workaround for Bun 1.3.14 reusing a connection the server refused with 413. Bun 1.4.2 never reuses it, so that row survives there. Rows are command rows: `{test}` is a Bun `-t` filter, a regular expression over the full test name (describe names and test name joined by spaces), so ids are anchored, escaped, and spell each space `\s`. The shared `scripts/list-bun-tests.mjs` asks Bun's JUnit reporter to list every discovered test as skipped with a never-matching selector, then reconstructs full names from nested describe suites and filters them with the row's JavaScript regular expression. It does not duplicate Bun's test-name formatting or run test bodies. `ckdev-mutate check --strict` verifies each active command row's `expect_red` selects a discovered test. CI replays the rows a pull request's diff selects, the full catalogue on every push to main, and the full catalogue with `--broad` nightly. Never `git checkout` a file while a replay runs: it removes the mutation and fakes a survivor.
25
-
26
10
  Licensed under MIT; see [LICENSE](LICENSE).
@@ -18,6 +18,14 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
18
18
  tokenPath: string;
19
19
  family: ClaustrumFamily;
20
20
  connect: () => Promise<ClaustrumScopedClient>;
21
+ /**
22
+ * How long one `connect()` attempt may take before this consumer treats the
23
+ * vault as unreachable (default 10 s). A connect that never settles would
24
+ * otherwise leave every later `refresh()` waiting on the same promise. After
25
+ * the limit the waiters get an unreachable error, the next `refresh()`
26
+ * connects again, and a client that arrives late is closed.
27
+ */
28
+ connectTimeoutMs?: number;
21
29
  /**
22
30
  * Whether the plugin currently takes its accounts from the vault (custody
23
31
  * mode) rather than from local logins. Checked before every discovery,
@@ -116,6 +124,12 @@ export interface HubMemberHooks {
116
124
  projection(): ProjectionOptions;
117
125
  onError(error: unknown): void;
118
126
  }
127
+ /**
128
+ * How long one connect attempt may take by default. It bounds a connect that
129
+ * never settles; the client's own handshake limit is not guaranteed to cover
130
+ * every stall, and callers waiting on discovery need an answer either way.
131
+ */
132
+ export declare const DEFAULT_CONNECT_TIMEOUT_MS = 10000;
119
133
  /**
120
134
  * Build the consumer for one hub member. `options` holds only what the member
121
135
  * uses: the hub's roster path for this member and the member's own fields.
@@ -1,5 +1,6 @@
1
1
  import { createLogger } from '../logger/index.js';
2
2
  import { combineAbortSignals } from '../util/any-signal.js';
3
+ import { ClaustrumUnreachableError } from './availability.js';
3
4
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
4
5
  import { readClaustrumEnrollmentToken } from './enrollment.js';
5
6
  import { ClaustrumConsumerError } from './errors.js';
@@ -8,6 +9,16 @@ import { pendingVaultQuota, retainVaultQuotaWriter } from './quota-writer.js';
8
9
  import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, vaultRoutingRows, } from './roster.js';
9
10
  import { drainShutdown, shutdownWarning } from './shutdown.js';
10
11
  import { SAFETY_POLL_MS } from './watch.js';
12
+ /**
13
+ * How long one connect attempt may take by default. It bounds a connect that
14
+ * never settles; the client's own handshake limit is not guaranteed to cover
15
+ * every stall, and callers waiting on discovery need an answer either way.
16
+ */
17
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
18
+ /** An unreachable vault, raised when a connect passed its time limit. */
19
+ function unreachableConnect() {
20
+ return new ClaustrumUnreachableError();
21
+ }
11
22
  let buildHubMember;
12
23
  /**
13
24
  * Build the consumer for one hub member. `options` holds only what the member
@@ -125,36 +136,69 @@ export class ClaustrumConsumer {
125
136
  if (this.#custody)
126
137
  return this.#custody;
127
138
  if (!this.#connecting) {
128
- this.#connecting = this.#options
129
- .connect()
130
- .then((client) => {
131
- if (this.#shutdown.signal.aborted) {
132
- client.close();
133
- this.#assertOpen();
134
- }
135
- this.#custody = new ClaustrumScopedCustody({
136
- client,
137
- family: this.#options.family,
138
- tokenPath: this.#options.tokenPath,
139
- parseIdentity: this.#options.parseIdentity,
140
- requireAssertion: this.#options.requireAssertion,
141
- now: this.#options.now,
142
- logger: this.#logger,
143
- setTimeoutImpl: this.#options.setTimeoutImpl,
144
- clearTimeoutImpl: this.#options.clearTimeoutImpl,
145
- });
146
- if (this.#options.insula && client.insula) {
147
- this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
148
- }
149
- return this.#custody;
150
- })
151
- .finally(() => {
152
- this.#connecting = undefined;
153
- });
139
+ // A connect that never settles must not hold #connecting open: every
140
+ // later refresh would wait on the same promise. The race below bounds
141
+ // each attempt, and only a client that arrives in time is installed.
142
+ const attempt = { timedOut: false };
143
+ this.#connecting = this.#boundedConnect(attempt);
154
144
  this.#track(this.#connecting);
155
145
  }
156
146
  return this.#wait(this.#connecting);
157
147
  }
148
+ /**
149
+ * One `connect()` attempt under `connectTimeoutMs`. The late promise is still
150
+ * observed after the deadline, so a client that arrives then is closed
151
+ * rather than leaked.
152
+ */
153
+ #boundedConnect(attempt) {
154
+ const setTimer = this.#options.setTimeoutImpl ?? setTimeout;
155
+ const clearTimer = this.#options.clearTimeoutImpl ?? clearTimeout;
156
+ const pending = this.#options.connect().then((client) => {
157
+ if (this.#shutdown.signal.aborted || attempt.timedOut) {
158
+ client.close();
159
+ if (!attempt.timedOut)
160
+ this.#assertOpen();
161
+ throw unreachableConnect();
162
+ }
163
+ this.#custody = new ClaustrumScopedCustody({
164
+ client,
165
+ family: this.#options.family,
166
+ tokenPath: this.#options.tokenPath,
167
+ parseIdentity: this.#options.parseIdentity,
168
+ requireAssertion: this.#options.requireAssertion,
169
+ now: this.#options.now,
170
+ logger: this.#logger,
171
+ setTimeoutImpl: this.#options.setTimeoutImpl,
172
+ clearTimeoutImpl: this.#options.clearTimeoutImpl,
173
+ });
174
+ if (this.#options.insula && client.insula) {
175
+ this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
176
+ }
177
+ return this.#custody;
178
+ });
179
+ let timer;
180
+ const deadline = new Promise((_resolve, reject) => {
181
+ timer = setTimer(() => {
182
+ attempt.timedOut = true;
183
+ if (this.#shutdown.signal.aborted)
184
+ return;
185
+ this.#logger.warn('vault connect timed out', {
186
+ reason: 'unreachable',
187
+ connectTimeoutMs: this.#connectTimeoutMs(),
188
+ });
189
+ reject(unreachableConnect());
190
+ }, this.#connectTimeoutMs());
191
+ timer.unref?.();
192
+ });
193
+ return Promise.race([pending, deadline]).finally(() => {
194
+ if (timer)
195
+ clearTimer(timer);
196
+ this.#connecting = undefined;
197
+ });
198
+ }
199
+ #connectTimeoutMs() {
200
+ return this.#options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
201
+ }
158
202
  /** The last committed roster this instance saw, without any I/O. */
159
203
  snapshot() {
160
204
  return this.#roster;
@@ -3,6 +3,7 @@ import { constants as fsConstants } from 'node:fs';
3
3
  import { chmod, mkdir, open, readFile, realpath, rename, stat, unlink, } from 'node:fs/promises';
4
4
  import { basename, dirname, extname, isAbsolute, join, resolve, } from 'node:path';
5
5
  import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile, } from '@cortexkit/claustrum-client';
6
+ import { FileReadCache } from '../fs/file-read-cache.js';
6
7
  import { acquireRefreshFileLock } from '../fs/index.js';
7
8
  import { ensurePrivateDirectory as ensureWindowsDirectory, PrivateFileError, readPrivateText, verifySafeDirectory, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
8
9
  import { ClaustrumConsumerError } from './errors.js';
@@ -402,32 +403,56 @@ async function writeStateAtomic(path, state, ancestorOptions = {}) {
402
403
  await unlink(temporary).catch(() => { });
403
404
  }
404
405
  }
406
+ const enrollmentStatusCache = new FileReadCache();
405
407
  export async function readClaustrumEnrollmentStatus(paths, proposedName) {
408
+ // Windows ACL, owner and ancestry checks are not represented by stat identity.
409
+ // Keep the native private-file validation and full read on every call there.
410
+ const result = windowsPrivateFiles
411
+ ? await readEnrollmentStatus(paths, proposedName)
412
+ : await enrollmentStatusCache.read([paths.tokenPath, paths.statePath], async ([tokenPath = paths.tokenPath, statePath = paths.statePath]) => readEnrollmentStatus({ tokenPath, statePath }, proposedName), (identities) => {
413
+ // Recheck the current effective user as well as mode and regular-file kind.
414
+ // lstat probes also prevent a link to the old inode from becoming a hit.
415
+ for (const metadata of identities)
416
+ if (metadata !== 'absent')
417
+ validateReadableSecretFile(metadata);
418
+ });
419
+ const status = { ...result.status };
420
+ if (result.usesProposedName && status.state === 'approved')
421
+ status.proposedName = proposedName;
422
+ return status;
423
+ }
424
+ async function readEnrollmentStatus(paths, proposedName) {
406
425
  const tokenValue = await readBoundedJson(paths.tokenPath);
407
426
  const token = tokenValue === undefined ? undefined : decodeTokenFile(tokenValue);
408
427
  const stateValue = await readBoundedJson(paths.statePath);
409
428
  const state = stateValue === undefined ? undefined : decodeEnrollmentState(stateValue);
410
429
  if (token) {
411
430
  return {
412
- state: 'approved',
413
- proposedName: state?.proposedName ?? proposedName,
414
- ...(state?.phase === 'approved' &&
415
- state.approvedName !== undefined && {
416
- approvedName: state.approvedName,
417
- }),
418
- tokenGeneration: token.token_generation,
431
+ usesProposedName: state === undefined,
432
+ status: {
433
+ state: 'approved',
434
+ proposedName: state?.proposedName ?? proposedName,
435
+ ...(state?.phase === 'approved' &&
436
+ state.approvedName !== undefined && {
437
+ approvedName: state.approvedName,
438
+ }),
439
+ tokenGeneration: token.token_generation,
440
+ },
419
441
  };
420
442
  }
421
443
  if (!state)
422
- return { state: 'idle' };
444
+ return { status: { state: 'idle' }, usesProposedName: false };
423
445
  if (state.phase === 'approved') {
424
446
  return {
425
- state: 'blocked',
426
- proposedName: state.proposedName,
427
- code: 'missing_token',
447
+ usesProposedName: false,
448
+ status: {
449
+ state: 'blocked',
450
+ proposedName: state.proposedName,
451
+ code: 'missing_token',
452
+ },
428
453
  };
429
454
  }
430
- return statusFromState(state);
455
+ return { status: statusFromState(state), usesProposedName: false };
431
456
  }
432
457
  /**
433
458
  * Resolve the host's account mode from its enrollment files. It never changes
@@ -47,6 +47,14 @@ export interface ClaustrumDiscoveryHubOptions {
47
47
  */
48
48
  family: ClassifyingClaustrumFamily<string>;
49
49
  connect: () => Promise<ClaustrumScopedClient>;
50
+ /**
51
+ * How long one `connect()` attempt may take before the hub treats the vault
52
+ * as unreachable (default 10 s, as `ClaustrumConsumerOptions`). The hub's
53
+ * connect is shared by every member waiting for a lease, so an attempt that
54
+ * never settles would hold every one of them; after the limit they get an
55
+ * unreachable error and the next acquire connects again.
56
+ */
57
+ connectTimeoutMs?: number;
50
58
  /**
51
59
  * Whether the plugin takes its accounts from the vault. Read from local
52
60
  * state only, never from the vault: on every hub tick, and when a member
@@ -15,7 +15,8 @@ import { readdir, stat } from 'node:fs/promises';
15
15
  import { join } from 'node:path';
16
16
  import { createLogger } from '../logger/index.js';
17
17
  import { combineAbortSignals } from '../util/any-signal.js';
18
- import { createHubMember, } from './consumer.js';
18
+ import { ClaustrumUnreachableError } from './availability.js';
19
+ import { createHubMember, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
19
20
  import { ClaustrumScopedCustody, } from './custody.js';
20
21
  import { ClaustrumConsumerError } from './errors.js';
21
22
  import { DEFAULT_ROUTE_PREFIX, decodedVaultRoster, forgetPendingVaultDiscovery, isVaultRosterLockRefusal, readVaultRoster, refreshVaultRoster, vaultRosterSeed, } from './roster.js';
@@ -98,6 +99,10 @@ function closed(message = 'Claustrum custody lease is closed') {
98
99
  function notActive() {
99
100
  return new ClaustrumConsumerError('not-active', 'Claustrum scoped custody is not active');
100
101
  }
102
+ /** An unreachable vault, raised when a connect passed its time limit. */
103
+ function unreachableConnect() {
104
+ return new ClaustrumUnreachableError();
105
+ }
101
106
  /**
102
107
  * Follow `pending`, but reject as soon as `signal` aborts. `pending` is
103
108
  * still observed afterwards, so its rejection is never unhandled.
@@ -321,31 +326,54 @@ export class ClaustrumDiscoveryHub {
321
326
  }
322
327
  #connect(generation) {
323
328
  const pending = this.#connecting;
324
- if (pending?.generation === generation)
329
+ if (pending?.generation === generation && pending.promise)
325
330
  return pending.promise;
326
- const entry = {
327
- generation,
328
- promise: this.#track(this.#options.connect().then((client) => {
329
- // A connect resolves into its generation only while that generation
330
- // is current and still wanted; otherwise its client never serves.
331
- if (!this.#live(generation) || generation.count <= 0) {
332
- client.close();
333
- throw closed('Claustrum connection is no longer wanted');
334
- }
335
- generation.custody = new ClaustrumScopedCustody({
336
- client,
337
- family: this.#options.family,
338
- tokenPath: this.#options.tokenPath,
339
- parseIdentity: this.#options.parseIdentity,
340
- requireAssertion: this.#options.requireAssertion,
341
- now: this.#options.now,
342
- logger: this.#logger,
343
- setTimeoutImpl: this.#options.setTimeoutImpl,
344
- clearTimeoutImpl: this.#options.clearTimeoutImpl,
331
+ const entry = { generation, timedOut: false };
332
+ // Every acquirer waits on this one connect, so it is bounded: a connect
333
+ // that never settles would otherwise hold them all for the hub's life.
334
+ const connectTimeoutMs = this.#options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
335
+ let timer;
336
+ const connect = this.#options.connect().then((client) => {
337
+ // A connect resolves into its generation only while that generation
338
+ // is current and still wanted; otherwise its client never serves.
339
+ if (entry.timedOut) {
340
+ client.close();
341
+ throw unreachableConnect();
342
+ }
343
+ if (!this.#live(generation) || generation.count <= 0) {
344
+ client.close();
345
+ throw closed('Claustrum connection is no longer wanted');
346
+ }
347
+ generation.custody = new ClaustrumScopedCustody({
348
+ client,
349
+ family: this.#options.family,
350
+ tokenPath: this.#options.tokenPath,
351
+ parseIdentity: this.#options.parseIdentity,
352
+ requireAssertion: this.#options.requireAssertion,
353
+ now: this.#options.now,
354
+ logger: this.#logger,
355
+ setTimeoutImpl: this.#options.setTimeoutImpl,
356
+ clearTimeoutImpl: this.#options.clearTimeoutImpl,
357
+ });
358
+ return generation.custody;
359
+ });
360
+ const deadline = new Promise((_resolve, reject) => {
361
+ timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
362
+ entry.timedOut = true;
363
+ if (!this.#live(generation))
364
+ return;
365
+ this.#logger.warn('vault connect timed out', {
366
+ reason: 'unreachable',
367
+ connectTimeoutMs,
345
368
  });
346
- return generation.custody;
347
- })),
348
- };
369
+ reject(unreachableConnect());
370
+ }, connectTimeoutMs);
371
+ timer.unref?.();
372
+ });
373
+ entry.promise = this.#track(Promise.race([connect, deadline]).finally(() => {
374
+ if (timer)
375
+ (this.#options.clearTimeoutImpl ?? clearTimeout)(timer);
376
+ }));
349
377
  // Clear only this connect: an older generation's connect settling late
350
378
  // must leave a newer generation's pending connect in place.
351
379
  const settled = entry.promise.finally(() => {
@@ -2,7 +2,7 @@ import { type ClaustrumClientOptions } from '@cortexkit/claustrum-client';
2
2
  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
- export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, type SendOptions, } from './consumer.js';
5
+ export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, DEFAULT_CONNECT_TIMEOUT_MS, type SendOptions, } from './consumer.js';
6
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';
@@ -13,11 +13,20 @@ export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from
13
13
  export { drainVaultQuota } from './quota-writer.js';
14
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';
15
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';
16
+ /** How long `connectClaustrumScopedClient` waits by default. */
17
+ export declare const SCOPED_CONNECT_TIMEOUT_MS = 10000;
16
18
  /**
17
19
  * Connect the client that lists and fetches this consumer's vault credentials
18
20
  * on the request path. `connectionFile` is required: this library
19
21
  * reads no environment, so the plugin resolves the vault's connection file.
22
+ *
23
+ * The wait is bounded by `connectTimeoutMs` (default 10 s) so a connect that
24
+ * never settles cannot leave a consumer with a pending connection forever; the
25
+ * caller then gets an unreachable error and may try again. A socket handshake
26
+ * has its own limit, but local reads before it (the connection file) do not,
27
+ * and a client that arrives after this deadline is closed, not returned.
20
28
  */
21
29
  export declare function connectClaustrumScopedClient(options: ClaustrumClientOptions & {
22
30
  connectionFile: string;
31
+ connectTimeoutMs?: number;
23
32
  }): Promise<ClaustrumScopedClient>;
@@ -4,10 +4,11 @@
4
4
  // declined-account interlock and the host-slot guard. Needs the optional
5
5
  // peer `@cortexkit/claustrum-client`.
6
6
  import { ClaustrumClient, } from '@cortexkit/claustrum-client';
7
+ import { ClaustrumUnreachableError } from './availability.js';
7
8
  import { insulaUsageTransport } from './insula.js';
8
9
  export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
9
10
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from './availability.js';
10
- export { ClaustrumConsumer, } from './consumer.js';
11
+ export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
11
12
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from './custody.js';
12
13
  export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
13
14
  export { ClaustrumConsumerError, } from './errors.js';
@@ -18,12 +19,43 @@ export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
18
19
  export { drainVaultQuota } from './quota-writer.js';
19
20
  export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, vaultRosterSeed, vaultRoutingRows, } from './roster.js';
20
21
  export { ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, WATCH_RETRY_MS, } from './watch.js';
22
+ /** How long `connectClaustrumScopedClient` waits by default. */
23
+ export const SCOPED_CONNECT_TIMEOUT_MS = 10_000;
21
24
  /**
22
25
  * Connect the client that lists and fetches this consumer's vault credentials
23
26
  * on the request path. `connectionFile` is required: this library
24
27
  * reads no environment, so the plugin resolves the vault's connection file.
28
+ *
29
+ * The wait is bounded by `connectTimeoutMs` (default 10 s) so a connect that
30
+ * never settles cannot leave a consumer with a pending connection forever; the
31
+ * caller then gets an unreachable error and may try again. A socket handshake
32
+ * has its own limit, but local reads before it (the connection file) do not,
33
+ * and a client that arrives after this deadline is closed, not returned.
25
34
  */
26
35
  export async function connectClaustrumScopedClient(options) {
27
- const client = await ClaustrumClient.connect(options);
28
- return Object.assign(client, { insula: insulaUsageTransport(options) });
36
+ const { connectTimeoutMs, ...client } = options;
37
+ const limit = connectTimeoutMs ?? SCOPED_CONNECT_TIMEOUT_MS;
38
+ const connecting = ClaustrumClient.connect(client);
39
+ let expired = false;
40
+ let timer;
41
+ const deadline = new Promise((_resolve, reject) => {
42
+ timer = setTimeout(() => {
43
+ expired = true;
44
+ reject(new ClaustrumUnreachableError());
45
+ }, limit);
46
+ timer.unref?.();
47
+ });
48
+ try {
49
+ const client = await Promise.race([connecting, deadline]);
50
+ return Object.assign(client, { insula: insulaUsageTransport(options) });
51
+ }
52
+ catch (error) {
53
+ // A connection that arrives after the deadline still owns a socket.
54
+ void connecting.then((client) => client.close(), () => { });
55
+ throw error;
56
+ }
57
+ finally {
58
+ if (!expired && timer)
59
+ clearTimeout(timer);
60
+ }
29
61
  }
@@ -1,3 +1,4 @@
1
+ import { type QuotaCommitTimer } from '../quota/commit-interval.js';
1
2
  import { type QuotaObservation } from '../quota/index.js';
2
3
  import { type QuotaReceipt, type VaultRosterFile } from './roster.js';
3
4
  export type VaultQuotaPublication = {
@@ -8,11 +9,17 @@ export type VaultQuotaPublication = {
8
9
  };
9
10
  type Listener = (publication: VaultQuotaPublication) => void;
10
11
  /** Retain the shared writer; the last consumer's close drains it. */
11
- export declare function retainVaultQuotaWriter(path: string, listener: Listener): () => Promise<void>;
12
+ export declare function retainVaultQuotaWriter(path: string, listener: Listener, clock?: QuotaCommitTimer): () => Promise<void>;
12
13
  /** Enqueue without filesystem work; each quota field retains its own receipt fence. */
13
14
  export declare function enqueueVaultQuota(path: string, publication: VaultQuotaPublication): Promise<boolean>;
14
15
  /** Overlay uncommitted observations when a consumer reloads the durable roster. */
15
16
  export declare function pendingVaultQuota(path: string, roster: VaultRosterFile | undefined): VaultRosterFile | undefined;
17
+ /**
18
+ * Whether this process holds quota readings for `path` that no commit of the
19
+ * durable roster has written yet, so a reader of the file alone is not seeing
20
+ * everything this process would publish.
21
+ */
22
+ export declare function hasPendingVaultQuota(path: string): boolean;
16
23
  /** Wait at most timeoutMs for detached publication; shutdown loss is acceptable. */
17
24
  export declare function drainVaultQuota(path: string, timeoutMs?: number): Promise<void>;
18
25
  export {};
@@ -1,5 +1,6 @@
1
1
  import { resolve } from 'node:path';
2
2
  import { createLogger } from '../logger/index.js';
3
+ import { QUOTA_COMMIT_INTERVAL_MS, quotaCommitTimer, } from '../quota/commit-interval.js';
3
4
  import { isQuotaObservation } from '../quota/index.js';
4
5
  import { quotaFields } from '../quota/pending.js';
5
6
  import { applyVaultQuota, mutateVaultRoster, } from './roster.js';
@@ -7,7 +8,7 @@ import { applyVaultQuota, mutateVaultRoster, } from './roster.js';
7
8
  const writers = new Map();
8
9
  const logger = createLogger('claustrum');
9
10
  const COALESCE_MS = 100;
10
- function writerFor(path) {
11
+ function writerFor(path, clock = quotaCommitTimer) {
11
12
  const key = resolve(path);
12
13
  let writer = writers.get(key);
13
14
  if (!writer) {
@@ -17,6 +18,7 @@ function writerFor(path) {
17
18
  listeners: new Set(),
18
19
  wake: new Set(),
19
20
  abort: new AbortController(),
21
+ clock,
20
22
  failures: 0,
21
23
  draining: false,
22
24
  order: 0,
@@ -26,8 +28,8 @@ function writerFor(path) {
26
28
  return writer;
27
29
  }
28
30
  /** Retain the shared writer; the last consumer's close drains it. */
29
- export function retainVaultQuotaWriter(path, listener) {
30
- const writer = writerFor(path);
31
+ export function retainVaultQuotaWriter(path, listener, clock) {
32
+ const writer = writerFor(path, clock);
31
33
  writer.listeners.add(listener);
32
34
  let released;
33
35
  return () => (released ??= (() => {
@@ -93,37 +95,57 @@ export function pendingVaultQuota(path, roster) {
93
95
  }
94
96
  return roster;
95
97
  }
98
+ /**
99
+ * Whether this process holds quota readings for `path` that no commit of the
100
+ * durable roster has written yet, so a reader of the file alone is not seeing
101
+ * everything this process would publish.
102
+ */
103
+ export function hasPendingVaultQuota(path) {
104
+ return !!writers.get(resolve(path))?.pending.size;
105
+ }
96
106
  function schedule(writer, delay) {
97
107
  if (writer.running ||
98
108
  writer.timer ||
99
109
  !writer.pending.size ||
100
110
  writer.abort.signal.aborted)
101
111
  return;
102
- writer.timer = setTimeout(() => {
112
+ const remaining = writer.draining
113
+ ? 0
114
+ : (writer.committedAt ?? -Infinity) +
115
+ QUOTA_COMMIT_INTERVAL_MS -
116
+ writer.clock.now();
117
+ writer.timer = writer.clock.schedule(Math.max(delay, remaining), () => {
103
118
  writer.timer = undefined;
104
- flush(writer);
105
- }, delay);
119
+ return flush(writer);
120
+ });
106
121
  if (!writer.draining)
107
122
  writer.timer.unref?.();
108
123
  }
124
+ function cancelTimer(writer) {
125
+ writer.timer?.cancel();
126
+ writer.timer = undefined;
127
+ }
109
128
  function flush(writer) {
110
129
  if (writer.running || writer.abort.signal.aborted)
111
- return;
130
+ return writer.running ?? Promise.resolve();
112
131
  const batch = new Map([...writer.pending].map(([account, pending]) => [
113
132
  account,
114
133
  new Map(pending),
115
134
  ]));
116
135
  writer.running = (async () => {
117
136
  try {
118
- await mutateVaultRoster(writer.path, (current) => {
137
+ const committed = await mutateVaultRoster(writer.path, (current) => {
119
138
  let next = current;
120
139
  for (const field of orderedFields(batch)) {
121
140
  if (field.priorReading)
122
141
  next = applyVaultQuota(next, field.priorReading).roster;
123
142
  next = applyVaultQuota(next, field.publication).roster;
124
143
  }
125
- return { ...(next !== current && { next }), result: undefined };
144
+ const changed = JSON.stringify(next) !== JSON.stringify(current);
145
+ return { ...(changed && { next }), result: changed };
126
146
  }, { signal: writer.abort.signal });
147
+ if (committed)
148
+ writer.committedAt = writer.clock.now();
127
149
  for (const [account, fields] of batch) {
128
150
  const pending = writer.pending.get(account);
129
151
  for (const [key, field] of fields) {
@@ -155,6 +177,7 @@ function flush(writer) {
155
177
  schedule(writer, backoff);
156
178
  }
157
179
  })();
180
+ return writer.running;
158
181
  }
159
182
  /** Wait at most timeoutMs for detached publication; shutdown loss is acceptable. */
160
183
  export async function drainVaultQuota(path, timeoutMs = 1_000) {
@@ -163,8 +186,7 @@ export async function drainVaultQuota(path, timeoutMs = 1_000) {
163
186
  if (!writer)
164
187
  return;
165
188
  writer.draining = true;
166
- clearTimeout(writer.timer);
167
- writer.timer = undefined;
189
+ cancelTimer(writer);
168
190
  let deadline;
169
191
  let wake;
170
192
  const drained = new Promise((done) => {
@@ -194,7 +216,7 @@ export async function drainVaultQuota(path, timeoutMs = 1_000) {
194
216
  // must not discard its observations or stop its retries.
195
217
  if (!writer.listeners.size) {
196
218
  writer.abort.abort();
197
- clearTimeout(writer.timer);
219
+ cancelTimer(writer);
198
220
  writer.pending.clear();
199
221
  if (writers.get(key) === writer)
200
222
  writers.delete(key);
@@ -231,7 +231,8 @@ export declare function isVaultRosterLockRefusal(path: string, error: unknown):
231
231
  * failed list, or custody switching off mid-run, never writes anything; a
232
232
  * peer holding the lease means its last committed roster is served instead.
233
233
  * A write-lock timeout keeps the discovered inventory for the next poll,
234
- * unless a peer has superseded its base view in the meantime.
234
+ * unless a peer has superseded its base view in the meantime. A list that
235
+ * would write the file the roster already holds takes no write lock at all.
235
236
  */
236
237
  export declare function refreshVaultRoster(options: {
237
238
  path: string;
@@ -1,11 +1,12 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { stat } from 'node:fs/promises';
2
3
  import { resolve } from 'node:path';
3
4
  import { acquireRefreshFileLock, LockContentionError, LockOwnershipError, lockPathFor, PrivateFileError, withLock, writeJsonAtomic, } from '../fs/index.js';
4
5
  import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
5
6
  import { decodeQuotaMap, isQuotaObservation, mergeQuotaObservation, } from '../quota/index.js';
6
7
  import { ClaustrumConsumerError } from './errors.js';
7
8
  import { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
8
- import { enqueueVaultQuota, pendingVaultQuota, } from './quota-writer.js';
9
+ import { enqueueVaultQuota, hasPendingVaultQuota, pendingVaultQuota, } from './quota-writer.js';
9
10
  export { drainVaultQuota } from './quota-writer.js';
10
11
  /** Declines and account order of `roster`, and nothing else of it. */
11
12
  export function vaultRosterSeed(roster) {
@@ -624,6 +625,75 @@ export function isVaultRosterLockRefusal(path, error) {
624
625
  }
625
626
  return false;
626
627
  }
628
+ const UNLOCKED_READ_ATTEMPTS = 4;
629
+ /**
630
+ * What identifies one version of the file at `path`: the roster is always
631
+ * replaced by a rename, so any write gives it a different inode, and an
632
+ * in-place rewrite a different size or modification time. Undefined when it
633
+ * cannot be inspected, which callers must read as 'may have changed'.
634
+ */
635
+ async function fileStamp(path) {
636
+ try {
637
+ const { dev, ino, size, mtimeMs } = await stat(path);
638
+ return { dev, ino, size, mtimeMs };
639
+ }
640
+ catch {
641
+ return undefined;
642
+ }
643
+ }
644
+ /** Whether two `fileStamp` readings are of the same file version. */
645
+ function sameFileStamp(left, right) {
646
+ return (left !== undefined &&
647
+ right !== undefined &&
648
+ left.dev === right.dev &&
649
+ left.ino === right.ino &&
650
+ left.size === right.size &&
651
+ left.mtimeMs === right.mtimeMs);
652
+ }
653
+ /**
654
+ * Whether a roster list that lands unlocked would write exactly the file at
655
+ * `path`. `overlay` names what this process holds besides the file: `target` is
656
+ * the file's own roster, which the locked commit compares against, and `local`,
657
+ * when different, is that roster plus unwritten quota readings, which must
658
+ * equal the commit's result too. Both must equal `next(target)`'s bytes, which
659
+ * is the write the commit would make; any difference, a missing or unreadable
660
+ * file, or a read that a concurrent reader keeps changing all mean 'commit'.
661
+ */
662
+ async function readUnlockedCommitTarget(path, overlay, next) {
663
+ for (let attempt = 0; attempt < UNLOCKED_READ_ATTEMPTS; attempt++) {
664
+ // Roster files are replaced by rename, so each attempt reads one whole
665
+ // file either way.
666
+ const before = await fileStamp(path);
667
+ const current = await readVaultRoster(path);
668
+ let target;
669
+ let local;
670
+ let changed;
671
+ try {
672
+ ;
673
+ ({ target, local } = overlay(current));
674
+ const written = JSON.stringify(next(target));
675
+ changed =
676
+ JSON.stringify(target) !== written ||
677
+ (local !== undefined && JSON.stringify(local) !== written);
678
+ }
679
+ catch {
680
+ return 'commit';
681
+ }
682
+ // No lock was taken, so another writer may have replaced the file while
683
+ // it was being projected. The answer must describe the file as it is now,
684
+ // otherwise a later list of the same roster would find it changed again.
685
+ if (!sameFileStamp(before, await fileStamp(path)))
686
+ continue;
687
+ if (changed)
688
+ return 'commit';
689
+ // Quota readings this process enqueued while the file was being projected
690
+ // are not part of `current`, and a list that returns unchanged while they
691
+ // wait would be the only chance to serve them as this list's roster. They
692
+ // keep their own commit either way, so this path takes the locked one.
693
+ return hasPendingVaultQuota(path) ? 'commit' : 'unchanged';
694
+ }
695
+ return 'commit';
696
+ }
627
697
  /**
628
698
  * Discover and commit the roster. The lease covers the list call and the
629
699
  * commit, not just the write: an opaque view cannot tell a delayed old reply
@@ -631,7 +701,8 @@ export function isVaultRosterLockRefusal(path, error) {
631
701
  * failed list, or custody switching off mid-run, never writes anything; a
632
702
  * peer holding the lease means its last committed roster is served instead.
633
703
  * A write-lock timeout keeps the discovered inventory for the next poll,
634
- * unless a peer has superseded its base view in the meantime.
704
+ * unless a peer has superseded its base view in the meantime. A list that
705
+ * would write the file the roster already holds takes no write lock at all.
635
706
  */
636
707
  export async function refreshVaultRoster(options) {
637
708
  options.signal?.throwIfAborted();
@@ -671,8 +742,44 @@ export async function refreshVaultRoster(options) {
671
742
  };
672
743
  pendingDiscoveries.delete(key);
673
744
  const { inventory } = discovered;
674
- options.onInventory?.(inventory);
745
+ // Called, not awaited: a caller noting the list here may wait for this
746
+ // roster's write lock, and this refresh decides below whether it needs it.
747
+ void options.onInventory?.(inventory);
675
748
  options.signal?.throwIfAborted();
749
+ const projection = typeof options.projection === 'function'
750
+ ? options.projection()
751
+ : options.projection;
752
+ const next = (current) => projectVaultRoster(current, inventory, projection);
753
+ const isActive = async () => {
754
+ options.signal?.throwIfAborted();
755
+ await lease.assertOwned();
756
+ return active();
757
+ };
758
+ // The write lock costs a lock file, an eviction marker and staging files in
759
+ // the roster's directory on every poll, so it is skipped when the list
760
+ // would write the file that is already there. The read deciding that takes
761
+ // no lock: a writer that commits between the read and this decision only
762
+ // makes our comparison stale, and a stale comparison never writes (the
763
+ // commit below judges the file again under the lock). Only equality with
764
+ // every byte the commit would write skips; every other answer commits.
765
+ const decision = await readUnlockedCommitTarget(options.path, (current) => {
766
+ // A hub member listed over a base view of its file: the file's own view
767
+ // is what the commit compares, so the overlay is the plain file. The
768
+ // locked commit below still applies the base-view rule.
769
+ if (listedOver)
770
+ return { target: current };
771
+ // This process's unwritten quota readings are part of the roster it
772
+ // serves, so a list that matches everything but them still commits.
773
+ const local = pendingVaultQuota(options.path, current);
774
+ return { target: current, ...(local !== current && { local }) };
775
+ }, next);
776
+ if (decision === 'unchanged') {
777
+ if (!(await isActive()))
778
+ return undefined;
779
+ // Returned as a later read of the file: that is what today's locked
780
+ // unchanged commit returns, and memory keeps only what was committed.
781
+ return await readVaultRoster(options.path);
782
+ }
676
783
  return await mutateVaultRoster(options.path, async (current) => {
677
784
  if (!(await active()))
678
785
  return { result: undefined };
@@ -682,12 +789,9 @@ export async function refreshVaultRoster(options) {
682
789
  current?.view !== listedOver.view &&
683
790
  current?.view !== inventory.view)
684
791
  return { result: current };
685
- const projection = typeof options.projection === 'function'
686
- ? options.projection()
687
- : options.projection;
688
- const next = projectVaultRoster(current, inventory, projection);
689
- const changed = JSON.stringify(current) !== JSON.stringify(next);
690
- return { ...(changed && { next }), result: next };
792
+ const projected = next(current);
793
+ const changed = JSON.stringify(current) !== JSON.stringify(projected);
794
+ return { ...(changed && { next: projected }), result: projected };
691
795
  }, {
692
796
  signal: options.signal,
693
797
  beforePublish: async () => {
@@ -0,0 +1,8 @@
1
+ import type { Stats } from 'node:fs';
2
+ type FileIdentity = Stats | 'absent';
3
+ /** Process-local reads, capped at 64 path sets with one value per resolved set. */
4
+ export declare class FileReadCache<T> {
5
+ #private;
6
+ read(paths: readonly string[], read: (resolvedPaths: string[]) => Promise<T>, validateHit?: (identities: readonly FileIdentity[]) => void): Promise<T>;
7
+ }
8
+ export {};
@@ -0,0 +1,57 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ async function identity(path) {
4
+ try {
5
+ const metadata = await lstat(path);
6
+ // Do not follow a symlink: its target can change without changing the link.
7
+ return metadata.isFile() ? metadata : undefined;
8
+ }
9
+ catch (error) {
10
+ return error.code === 'ENOENT'
11
+ ? 'absent'
12
+ : undefined;
13
+ }
14
+ }
15
+ function sameIdentity(left, right) {
16
+ if (left === 'absent' || right === 'absent')
17
+ return left === right;
18
+ return (left.dev === right.dev &&
19
+ left.ino === right.ino &&
20
+ left.size === right.size &&
21
+ left.mtimeMs === right.mtimeMs &&
22
+ left.ctimeMs === right.ctimeMs);
23
+ }
24
+ /** Process-local reads, capped at 64 path sets with one value per resolved set. */
25
+ export class FileReadCache {
26
+ #entries = new Map();
27
+ async read(paths, read, validateHit) {
28
+ const resolvedPaths = paths.map((path) => resolve(path));
29
+ const key = JSON.stringify(resolvedPaths);
30
+ const probed = await Promise.all(resolvedPaths.map(identity));
31
+ const identities = probed.every((entry) => entry !== undefined)
32
+ ? probed
33
+ : undefined;
34
+ const cached = this.#entries.get(key);
35
+ if (identities &&
36
+ cached &&
37
+ identities.every((entry, index) => {
38
+ const previous = cached.identities[index];
39
+ return previous !== undefined && sameIdentity(entry, previous);
40
+ })) {
41
+ validateHit?.(identities);
42
+ return cached.value;
43
+ }
44
+ // A failed probe or read must not leave a previous successful value reusable.
45
+ this.#entries.delete(key);
46
+ const value = await read(resolvedPaths);
47
+ if (identities) {
48
+ if (this.#entries.size >= 64) {
49
+ const oldest = this.#entries.keys().next().value;
50
+ if (oldest !== undefined)
51
+ this.#entries.delete(oldest);
52
+ }
53
+ this.#entries.set(key, { identities, value });
54
+ }
55
+ return value;
56
+ }
57
+ }
@@ -0,0 +1,9 @@
1
+ export declare const QUOTA_COMMIT_INTERVAL_MS = 30000;
2
+ export interface QuotaCommitTimer {
3
+ now(): number;
4
+ schedule(delayMs: number, run: () => Promise<void>): {
5
+ cancel(): void;
6
+ unref?(): void;
7
+ };
8
+ }
9
+ export declare const quotaCommitTimer: QuotaCommitTimer;
@@ -0,0 +1,18 @@
1
+ // Atomic quota commits create locks, markers and a renamed temp file. Keep
2
+ // those filesystem events at least 30 s apart under normal load; routing sees
3
+ // pending readings immediately, while other processes may lag by one interval.
4
+ // Shutdown drains and a full bounded pool queue can commit sooner.
5
+ // The vault shares one gate per resolved path; each pool handle has its own.
6
+ // N pool handles on one file can therefore make N normal commits per interval
7
+ // in one process. These gates do not coordinate with other processes.
8
+ export const QUOTA_COMMIT_INTERVAL_MS = 30_000;
9
+ export const quotaCommitTimer = {
10
+ now: () => performance.now(),
11
+ schedule(delayMs, run) {
12
+ const timer = setTimeout(() => void run(), delayMs);
13
+ return {
14
+ cancel: () => clearTimeout(timer),
15
+ unref: () => timer.unref?.(),
16
+ };
17
+ },
18
+ };
@@ -52,6 +52,8 @@ export type ReadResult = ({
52
52
  kind?: 'snapshot-contended';
53
53
  retryable?: true;
54
54
  };
55
+ /** Settings need only the config classification, not a joined roster snapshot. */
56
+ export declare function readPoolConfig(path: string): Promise<import("./schema.js").ConfigClassification>;
55
57
  /**
56
58
  * Validate config/state/config bytes without locks. Roster replacement writes
57
59
  * config before deleting old state credentials. Re-read a changed config so an
@@ -28,6 +28,10 @@ function parseFile(text) {
28
28
  return { exists: true, parseError };
29
29
  }
30
30
  }
31
+ /** Settings need only the config classification, not a joined roster snapshot. */
32
+ export async function readPoolConfig(path) {
33
+ return classifyConfig(parseFile(await readText(path)));
34
+ }
31
35
  /**
32
36
  * Validate config/state/config bytes without locks. Roster replacement writes
33
37
  * config before deleting old state credentials. Re-read a changed config so an
@@ -1,3 +1,4 @@
1
+ import type { QuotaCommitTimer } from '../quota/commit-interval.js';
1
2
  import { type Attribution } from './attribution.js';
2
3
  import type { PoolOperationError } from './errors.js';
3
4
  import type { PoolLogger } from './hooks.js';
@@ -24,11 +25,15 @@ export interface OpenPoolStoreOptions {
24
25
  * older reading replaces. Accepted readings appear in read/load
25
26
  * immediately, merged the same way; the returned promise still rejects
26
27
  * current-row refusals before queueing. Await dispose or close at shutdown
27
- * to drain.
28
+ * to attempt a bounded drain; readings still pending at its timeout are
29
+ * discarded. Normal quota commits are at least 30 seconds apart; a full
30
+ * queue commits early so response handling never waits for that interval.
28
31
  */
29
32
  coalesceQuota?: boolean;
30
33
  /** Bounded quota drain on close/dispose, in milliseconds; defaults to 1,000. */
31
34
  quotaDrainTimeoutMs?: number;
35
+ /** Monotonic clock and scheduling seam for detached quota commits. */
36
+ quotaCommitTimer?: QuotaCommitTimer;
32
37
  /**
33
38
  * The codec of the provider state kept beside each row's credential (see
34
39
  * `ProviderStateCodec`). Without it no row shows a provider state, and
@@ -82,7 +82,7 @@ export function openPoolStore(options) {
82
82
  firePull: (id, reason) => pulls.fire(id, reason),
83
83
  };
84
84
  const quotaWriter = options.coalesceQuota
85
- ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs)
85
+ ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs, options.quotaCommitTimer)
86
86
  : undefined;
87
87
  const record = (id, attribution, observation) => quotaWriter
88
88
  ? quotaWriter.record(id, attribution, observation)
@@ -1,3 +1,4 @@
1
+ import { type QuotaCommitTimer } from '../quota/commit-interval.js';
1
2
  import { type Attribution } from './attribution.js';
2
3
  import { type StoreRuntime } from './runtime.js';
3
4
  import { type PoolRow } from './schema.js';
@@ -14,17 +15,19 @@ export declare const POOL_QUOTA_QUEUE_LIMIT = 128;
14
15
  export declare class PoolQuotaWriter {
15
16
  private readonly rt;
16
17
  private readonly timeoutMs;
18
+ private readonly clock;
17
19
  private readonly pending;
18
20
  private readonly warned;
19
21
  private readonly wake;
20
22
  private readonly logger;
21
23
  private timer?;
24
+ private committedAt?;
22
25
  private running?;
23
26
  private closing?;
24
27
  private closed;
25
28
  private stopped;
26
29
  private failures;
27
- constructor(rt: StoreRuntime, timeoutMs?: number);
30
+ constructor(rt: StoreRuntime, timeoutMs?: number, clock?: QuotaCommitTimer);
28
31
  record(id: string, attribution: Attribution, observation: unknown): Promise<void>;
29
32
  private queued;
30
33
  private room;
@@ -32,6 +35,7 @@ export declare class PoolQuotaWriter {
32
35
  private overlayRow;
33
36
  overlay(rows: PoolRow[]): PoolRow[];
34
37
  private schedule;
38
+ private cancelTimer;
35
39
  private flushNow;
36
40
  private flush;
37
41
  private warn;
@@ -1,4 +1,5 @@
1
1
  import { createLogger } from '../logger/index.js';
2
+ import { QUOTA_COMMIT_INTERVAL_MS, quotaCommitTimer, } from '../quota/commit-interval.js';
2
3
  import { assertQuotaEpoch, assertQuotaRow, mergedQuota, } from './attribution.js';
3
4
  import { PoolOperationError } from './errors.js';
4
5
  import { toFailure, withTransaction } from './mutate.js';
@@ -24,19 +25,22 @@ export const POOL_QUOTA_QUEUE_LIMIT = 128;
24
25
  export class PoolQuotaWriter {
25
26
  rt;
26
27
  timeoutMs;
28
+ clock;
27
29
  pending = new Map();
28
30
  warned = new Set();
29
31
  wake = new Set();
30
32
  logger;
31
33
  timer;
34
+ committedAt;
32
35
  running;
33
36
  closing;
34
37
  closed = false;
35
38
  stopped = false;
36
39
  failures = 0;
37
- constructor(rt, timeoutMs = 1_000) {
40
+ constructor(rt, timeoutMs = 1_000, clock = quotaCommitTimer) {
38
41
  this.rt = rt;
39
42
  this.timeoutMs = timeoutMs;
43
+ this.clock = clock;
40
44
  this.logger = rt.ctx.logger ?? createLogger('store');
41
45
  }
42
46
  async record(id, attribution, observation) {
@@ -126,25 +130,33 @@ export class PoolQuotaWriter {
126
130
  schedule(delay) {
127
131
  if (this.running || this.timer || !this.pending.size || this.stopped)
128
132
  return;
129
- this.timer = setTimeout(() => {
133
+ const remaining = this.closed
134
+ ? 0
135
+ : (this.committedAt ?? -Infinity) +
136
+ QUOTA_COMMIT_INTERVAL_MS -
137
+ this.clock.now();
138
+ this.timer = this.clock.schedule(Math.max(delay, remaining), () => {
130
139
  this.timer = undefined;
131
- this.flush();
132
- }, delay);
140
+ return this.flush();
141
+ });
133
142
  if (!this.closed)
134
143
  this.timer.unref?.();
135
144
  }
136
- // Starts a flush now rather than at the coalescing timer or retry backoff;
137
- // a flush already running is left to finish.
145
+ cancelTimer() {
146
+ this.timer?.cancel();
147
+ this.timer = undefined;
148
+ }
149
+ // A full queue overrides the interval: response handling must not wait for
150
+ // a quota commit slot. A flush already running is left to finish.
138
151
  flushNow() {
139
152
  if (this.running)
140
153
  return;
141
- clearTimeout(this.timer);
142
- this.timer = undefined;
154
+ this.cancelTimer();
143
155
  this.flush();
144
156
  }
145
157
  flush() {
146
158
  if (this.running || this.stopped || !this.pending.size)
147
- return;
159
+ return this.running ?? Promise.resolve();
148
160
  // Every queued reading, each row's in arrival order.
149
161
  const batch = [...this.pending.values()].flat();
150
162
  // Short lock attempts allow retries to pick up freshly queued readings and
@@ -208,8 +220,10 @@ export class PoolQuotaWriter {
208
220
  tx.setEntry(id, { ...entry, quota, needsFirstReading: false });
209
221
  changed = true;
210
222
  }
211
- if (changed && !this.stopped)
223
+ if (changed && !this.stopped) {
212
224
  await tx.commitConfig();
225
+ this.committedAt = this.clock.now();
226
+ }
213
227
  }, { completeTorn: false });
214
228
  const flushed = new Set(batch);
215
229
  for (const [id, queue] of this.pending) {
@@ -240,6 +254,7 @@ export class PoolQuotaWriter {
240
254
  this.schedule(delay);
241
255
  }
242
256
  })();
257
+ return this.running;
243
258
  }
244
259
  warn(message, data) {
245
260
  try {
@@ -257,8 +272,7 @@ export class PoolQuotaWriter {
257
272
  return this.closing;
258
273
  }
259
274
  async drain() {
260
- clearTimeout(this.timer);
261
- this.timer = undefined;
275
+ this.cancelTimer();
262
276
  let deadline;
263
277
  let wake;
264
278
  const drained = new Promise((done) => {
@@ -281,7 +295,7 @@ export class PoolQuotaWriter {
281
295
  finally {
282
296
  this.stopped = true;
283
297
  clearTimeout(deadline);
284
- clearTimeout(this.timer);
298
+ this.cancelTimer();
285
299
  this.wake.delete(wake);
286
300
  if (this.pending.size)
287
301
  this.warn('pool quota drain timed out; pending readings left', {
@@ -50,7 +50,7 @@ export type UpdateSettingsResult = {
50
50
  /** `unchanged` when the mutator left the settings as they were; nothing was written. */
51
51
  outcome: 'updated' | 'unchanged';
52
52
  };
53
- /** Reads the settings without taking a lock or writing anything. */
53
+ /** Reads only the config's settings, without taking a lock or writing anything. */
54
54
  export declare function readPoolSettings(rt: StoreRuntime): Promise<SettingsRead>;
55
55
  /**
56
56
  * One locked read-modify-write of the plugin's settings in the config file
@@ -1,8 +1,10 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
2
  import { writeJsonAtomic } from '../fs/atomic-write.js';
3
+ import { FileReadCache } from '../fs/file-read-cache.js';
4
+ import { windowsPrivateFiles } from '../fs/private-files.js';
3
5
  import { PoolOperationError } from './errors.js';
4
6
  import { assertNotInsideHook, runInsideHook } from './hooks.js';
5
- import { notReadyError, readPool, runOperation } from './mutate.js';
7
+ import { notReadyError, readPool, readPoolConfig, runOperation, } from './mutate.js';
6
8
  import { isRecord, POOL_KEY } from './schema.js';
7
9
  /**
8
10
  * Top-level config keys the pool owns: the legacy `version`, the legacy
@@ -58,12 +60,20 @@ function settingsRefusal(message) {
58
60
  message,
59
61
  });
60
62
  }
61
- /** Reads the settings without taking a lock or writing anything. */
63
+ const settingsCache = new FileReadCache();
64
+ /** Reads only the config's settings, without taking a lock or writing anything. */
62
65
  export async function readPoolSettings(rt) {
63
- const result = await readPool(rt.ctx);
64
- if (result.status === 'error')
65
- return result;
66
- return { status: result.status, settings: settingsOf(result.config) };
66
+ const read = async ([configPath = rt.ctx.configPath,] = []) => {
67
+ const result = await readPoolConfig(configPath);
68
+ if (result.status === 'error')
69
+ return { status: 'error', file: 'config', reason: result.reason };
70
+ return { status: result.status, settings: settingsOf(result.config) };
71
+ };
72
+ // Native Windows security checks cannot be replaced by a stat fingerprint.
73
+ const result = windowsPrivateFiles
74
+ ? await read()
75
+ : await settingsCache.read([rt.ctx.configPath], read);
76
+ return structuredClone(result);
67
77
  }
68
78
  /**
69
79
  * One locked read-modify-write of the plugin's settings in the config file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.27.0",
3
+ "version": "0.27.1",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {