@cortexkit/common-auth 0.37.0 → 0.38.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.
@@ -120,6 +120,8 @@ export interface VaultRosterLockContext {
120
120
  }
121
121
  export interface MutateVaultRosterOptions {
122
122
  signal?: AbortSignal;
123
+ /** Runs under the roster lock once published, even if a later step fails. Must not throw. */
124
+ onPublished?: () => void;
123
125
  /**
124
126
  * Runs when the new roster is fully staged on disk, immediately before the
125
127
  * rename that publishes it, so a caller can confirm a lease of its own at
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { stat } from 'node:fs/promises';
3
3
  import { resolve } from 'node:path';
4
+ import { FileReadCache } from '../fs/file-read-cache.js';
4
5
  import { acquireRefreshFileLock, LockContentionError, LockOwnershipError, lockPathFor, PrivateFileError, withLock, writeJsonAtomic, } from '../fs/index.js';
5
6
  import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
6
7
  import { decodeQuotaMap, isQuotaObservation, mergeQuotaObservation, } from '../quota/index.js';
@@ -333,7 +334,18 @@ function decodeRoster(value) {
333
334
  export function decodedVaultRoster(roster) {
334
335
  return decodeRoster(JSON.parse(JSON.stringify(roster)));
335
336
  }
337
+ const rosterReadCache = new FileReadCache({
338
+ followSymlinks: true,
339
+ });
336
340
  export async function readVaultRoster(path) {
341
+ // Windows permission, owner and ancestry checks must still run on every read.
342
+ if (windowsPrivateFiles)
343
+ return readFreshVaultRoster(path);
344
+ const roster = await rosterReadCache.read([path], ([resolvedPath = path]) => readFreshVaultRoster(resolvedPath));
345
+ // Callers edit rows and nested limits data; none may own the cached objects.
346
+ return structuredClone(roster);
347
+ }
348
+ async function readFreshVaultRoster(path) {
337
349
  let text;
338
350
  try {
339
351
  text = await readPrivateText(path, windowsPrivateFiles);
@@ -366,7 +378,8 @@ const DISCOVERY_LEASE = { name: 'claustrum-roster', ttlMs: 30_000 };
366
378
  */
367
379
  export async function mutateVaultRoster(path, change, options = {}) {
368
380
  return withLock(path, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
369
- const current = await readVaultRoster(path);
381
+ // A read-modify-write always observes the file under its write lock.
382
+ const current = await readFreshVaultRoster(path);
370
383
  const { next, result } = await change(current, {
371
384
  assertOwned: () => lock.assertOwned(),
372
385
  });
@@ -374,13 +387,24 @@ export async function mutateVaultRoster(path, change, options = {}) {
374
387
  await lock.assertOwned();
375
388
  // Staging the file takes several awaited steps; check both the caller's
376
389
  // lease and this lock again at the last moment before the rename.
377
- await writeJsonAtomic(path, next, {
378
- beforeRename: async () => {
379
- await options.beforePublish?.();
380
- options.signal?.throwIfAborted();
381
- await lock.assertOwned();
382
- },
383
- });
390
+ try {
391
+ await writeJsonAtomic(path, next, {
392
+ beforeRename: async () => {
393
+ await options.beforePublish?.();
394
+ options.signal?.throwIfAborted();
395
+ await lock.assertOwned();
396
+ },
397
+ });
398
+ }
399
+ catch (error) {
400
+ if (error &&
401
+ typeof error === 'object' &&
402
+ 'published' in error &&
403
+ error.published === true)
404
+ options.onPublished?.();
405
+ throw error;
406
+ }
407
+ options.onPublished?.();
384
408
  }
385
409
  return result;
386
410
  });
@@ -3,6 +3,9 @@ type FileIdentity = Stats | 'absent';
3
3
  /** Process-local reads, capped at 64 path sets with one value per resolved set. */
4
4
  export declare class FileReadCache<T> {
5
5
  #private;
6
+ constructor(options?: {
7
+ followSymlinks?: boolean;
8
+ });
6
9
  read(paths: readonly string[], read: (resolvedPaths: string[]) => Promise<T>, validateHit?: (identities: readonly FileIdentity[]) => void): Promise<T>;
7
10
  }
8
11
  export {};
@@ -1,9 +1,10 @@
1
- import { lstat } from 'node:fs/promises';
1
+ import { lstat, stat } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
- async function identity(path) {
3
+ async function identity(path, followSymlinks) {
4
4
  try {
5
- const metadata = await lstat(path);
6
- // Do not follow a symlink: its target can change without changing the link.
5
+ // Match the reader: private readers reject links, while readFile follows
6
+ // them and needs the target's identity, not the link's identity.
7
+ const metadata = await (followSymlinks ? stat(path) : lstat(path));
7
8
  return metadata.isFile() ? metadata : undefined;
8
9
  }
9
10
  catch (error) {
@@ -23,11 +24,15 @@ function sameIdentity(left, right) {
23
24
  }
24
25
  /** Process-local reads, capped at 64 path sets with one value per resolved set. */
25
26
  export class FileReadCache {
27
+ #followSymlinks;
26
28
  #entries = new Map();
29
+ constructor(options = {}) {
30
+ this.#followSymlinks = options.followSymlinks ?? false;
31
+ }
27
32
  async read(paths, read, validateHit) {
28
33
  const resolvedPaths = paths.map((path) => resolve(path));
29
34
  const key = JSON.stringify(resolvedPaths);
30
- const probed = await Promise.all(resolvedPaths.map(identity));
35
+ const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
31
36
  const identities = probed.every((entry) => entry !== undefined)
32
37
  ? probed
33
38
  : undefined;
@@ -0,0 +1,32 @@
1
+ import type { LimitsRecoveryLogger } from './envelope-loss.js';
2
+ import type { LimitsNamespace } from './namespace.js';
3
+ export type LimitsAbandonReason = 'conflict' | 'unsupported';
4
+ declare const envelopeError: unique symbol;
5
+ /** Another writer replaced an envelope after this adapter already replaced one. */
6
+ export declare class LimitsEnvelopeConflictError extends Error {
7
+ readonly [envelopeError] = "conflict";
8
+ constructor();
9
+ }
10
+ /** The envelope belongs to a schema this version must never overwrite. */
11
+ export declare class LimitsEnvelopeUnsupportedError extends Error {
12
+ readonly [envelopeError] = "unsupported";
13
+ constructor();
14
+ }
15
+ export declare function limitsEnvelopeAbandonReason(error: unknown): LimitsAbandonReason | undefined;
16
+ type Replacement = 'foreign-namespace' | 'malformed';
17
+ interface DecodedEnvelope {
18
+ readonly snapshot?: LimitsNamespace;
19
+ readonly replacement?: Replacement;
20
+ }
21
+ /** Public calls and background envelope-loss repairs share one replacement allowance. */
22
+ export declare class EnvelopeGuard {
23
+ private readonly namespace;
24
+ private readonly logger?;
25
+ private replaced;
26
+ private terminal?;
27
+ constructor(namespace: string, logger?: LimitsRecoveryLogger | undefined);
28
+ assertWritable(): void;
29
+ decode(value: unknown): DecodedEnvelope;
30
+ didCommit(replacement: Replacement | undefined): boolean;
31
+ }
32
+ export {};
@@ -0,0 +1,123 @@
1
+ // Registries can be shared by independently bundled copies of common-auth.
2
+ const envelopeError = Symbol.for('@cortexkit/common-auth/limits-envelope-error');
3
+ /** Another writer replaced an envelope after this adapter already replaced one. */
4
+ export class LimitsEnvelopeConflictError extends Error {
5
+ [envelopeError] = 'conflict';
6
+ constructor() {
7
+ super('Conflicting limits envelope writers');
8
+ this.name = 'LimitsEnvelopeConflictError';
9
+ }
10
+ }
11
+ /** The envelope belongs to a schema this version must never overwrite. */
12
+ export class LimitsEnvelopeUnsupportedError extends Error {
13
+ [envelopeError] = 'unsupported';
14
+ constructor() {
15
+ super('Invalid or unsupported limits namespace schema');
16
+ this.name = 'LimitsEnvelopeUnsupportedError';
17
+ }
18
+ }
19
+ export function limitsEnvelopeAbandonReason(error) {
20
+ const reason = error && typeof error === 'object' && Reflect.get(error, envelopeError);
21
+ return reason === 'conflict' || reason === 'unsupported' ? reason : undefined;
22
+ }
23
+ function record(value) {
24
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
25
+ }
26
+ const revision = (value) => Number.isSafeInteger(value) && value >= 0;
27
+ const finite = (value) => typeof value === 'number' && Number.isFinite(value);
28
+ const cause = (value) => value === undefined || value === 'rate-limit' || value === 'payment-balance';
29
+ const arrayOf = (value, valid) => Array.isArray(value) && value.every(valid);
30
+ function account(value, namespace) {
31
+ return (record(value) &&
32
+ value.namespace === namespace &&
33
+ typeof value.accountId === 'string' &&
34
+ typeof value.incarnation === 'string');
35
+ }
36
+ function key(value, namespace) {
37
+ if (!record(value) || !record(value.scope))
38
+ return false;
39
+ const scope = value.scope;
40
+ return (account(value.account, namespace) &&
41
+ typeof value.window === 'string' &&
42
+ (scope.kind === 'pool' ||
43
+ (scope.kind === 'family' && typeof scope.family === 'string') ||
44
+ (scope.kind === 'model' && typeof scope.model === 'string')));
45
+ }
46
+ function validEnvelope(value, namespace) {
47
+ return (value.namespace === namespace &&
48
+ typeof value.generation === 'string' &&
49
+ revision(value.revision) &&
50
+ revision(value.lowWatermark) &&
51
+ arrayOf(value.marks, (mark) => record(mark) &&
52
+ key(mark.key, namespace) &&
53
+ ['latest-evidence', 'max-until', 'overwrite'].includes(mark.mergeLaw) &&
54
+ arrayOf(mark.entries, (entry) => record(entry) &&
55
+ cause(entry.cause) &&
56
+ finite(entry.until) &&
57
+ finite(entry.evidenceAt) &&
58
+ revision(entry.baseRevision) &&
59
+ revision(entry.committedRevision))) &&
60
+ arrayOf(value.tombstones, (clear) => record(clear) &&
61
+ key(clear.key, namespace) &&
62
+ revision(clear.revision) &&
63
+ cause(clear.cause)) &&
64
+ arrayOf(value.operationIds, (op) => record(op) &&
65
+ typeof op.producerId === 'string' &&
66
+ typeof op.operationId === 'string' &&
67
+ revision(op.revision)) &&
68
+ arrayOf(value.access, (access) => record(access) &&
69
+ account(access.account, namespace) &&
70
+ finite(access.eligibilityStateUpdatedAt) &&
71
+ revision(access.committedRevision)));
72
+ }
73
+ /** Public calls and background envelope-loss repairs share one replacement allowance. */
74
+ export class EnvelopeGuard {
75
+ namespace;
76
+ logger;
77
+ replaced = false;
78
+ terminal;
79
+ constructor(namespace, logger) {
80
+ this.namespace = namespace;
81
+ this.logger = logger;
82
+ }
83
+ assertWritable() {
84
+ if (this.terminal)
85
+ throw this.terminal;
86
+ }
87
+ decode(value) {
88
+ this.assertWritable();
89
+ if (value === undefined)
90
+ return {};
91
+ let replacement;
92
+ if (!record(value))
93
+ replacement = 'malformed';
94
+ else if (value.schemaVersion !== 1) {
95
+ this.terminal = new LimitsEnvelopeUnsupportedError();
96
+ throw this.terminal;
97
+ }
98
+ else if (typeof value.namespace === 'string' &&
99
+ value.namespace !== this.namespace)
100
+ replacement = 'foreign-namespace';
101
+ else if (!validEnvelope(value, this.namespace))
102
+ replacement = 'malformed';
103
+ if (!replacement)
104
+ return { snapshot: value };
105
+ if (this.replaced) {
106
+ this.terminal = new LimitsEnvelopeConflictError();
107
+ throw this.terminal;
108
+ }
109
+ return { replacement };
110
+ }
111
+ didCommit(replacement) {
112
+ if (!replacement || this.replaced)
113
+ return false;
114
+ this.replaced = true;
115
+ try {
116
+ this.logger?.warn(`limits envelope replaced: ${replacement}`);
117
+ }
118
+ catch {
119
+ // Diagnostics cannot change a durable replacement's result.
120
+ }
121
+ return true;
122
+ }
123
+ }
@@ -7,6 +7,7 @@ export type { HoldFacts, LimitCandidate, LimitDecision, ModeSelection, PolicyFac
7
7
  export { decideAfterLimit } from './decide.js';
8
8
  export type { ResetFormatInput, ResetFormatter } from './duration.js';
9
9
  export { formatDuration, formatReset } from './duration.js';
10
+ export { type LimitsAbandonReason, LimitsEnvelopeConflictError, LimitsEnvelopeUnsupportedError, } from './envelope.js';
10
11
  export type { BuiltRefusal, HostRetry, HttpRefusal, OpenCode1Family, RefusalFamily, RefusalInput, TextRefusal, ThrownRefusal, } from './families.js';
11
12
  export { buildRefusal, ClaudeIncompleteError, retryAfterSeconds, } from './families.js';
12
13
  export { classifyHeaders, classifyRetryAfter, resolveHeaderReset, resolveRetryAfter, } from './header-classifier.js';
@@ -22,6 +23,7 @@ export type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
22
23
  export { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
23
24
  export type { ClearTombstone, CommittedOperation, LimitsCommand, LimitsCommandOutcome, LimitsMergeContext, LimitsMergeResult, LimitsNamespace, LimitsRejection, MarkTarget, NamespaceAccess, NamespaceMark, TimedMarkKey, } from './namespace.js';
24
25
  export { applyLimitsCommands, createLimitsNamespace, LIMITS_HISTORY_BOUND, pruneLimitsNamespace, timedMarkKeyId, } from './namespace.js';
26
+ export { canonicalLimitsPath } from './path.js';
25
27
  export type { LimitsPersistenceCommit, LimitsPersistenceOutcome, LimitsPersistenceSnapshot, PersistenceAdapter, } from './persistence.js';
26
28
  export { LimitsPersistenceRefusal } from './persistence.js';
27
29
  export type { PiWaitOptions, PiWaitResult } from './pi-wait.js';
@@ -3,6 +3,7 @@ export { marksAfterSuccess } from './axes.js';
3
3
  export { toOpenCode2LimitSignal } from './bridge.js';
4
4
  export { decideAfterLimit } from './decide.js';
5
5
  export { formatDuration, formatReset } from './duration.js';
6
+ export { LimitsEnvelopeConflictError, LimitsEnvelopeUnsupportedError, } from './envelope.js';
6
7
  export { buildRefusal, ClaudeIncompleteError, retryAfterSeconds, } from './families.js';
7
8
  export { classifyHeaders, classifyRetryAfter, resolveHeaderReset, resolveRetryAfter, } from './header-classifier.js';
8
9
  export { MAX_SAME_ACCOUNT_HOLD_MS, readMaxSameAccountWait, sameAccountHoldFacts, } from './hold.js';
@@ -12,6 +13,7 @@ export { sanitizeRefusalLabel } from './labels.js';
12
13
  export { ANTIGRAVITY_FAILURE_LADDER, markFromSignal, markIsActive, reduceFailureHistory, } from './marker.js';
13
14
  export { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
14
15
  export { applyLimitsCommands, createLimitsNamespace, LIMITS_HISTORY_BOUND, pruneLimitsNamespace, timedMarkKeyId, } from './namespace.js';
16
+ export { canonicalLimitsPath } from './path.js';
15
17
  export { LimitsPersistenceRefusal } from './persistence.js';
16
18
  export { waitForPi } from './pi-wait.js';
17
19
  export { createPoolLimitsAdapter, } from './pool-adapter.js';
@@ -0,0 +1,2 @@
1
+ /** Canonicalize the parent even when the store file has not been created yet. */
2
+ export declare function canonicalLimitsPath(path: string): string;
@@ -0,0 +1,14 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ /** Canonicalize the parent even when the store file has not been created yet. */
4
+ export function canonicalLimitsPath(path) {
5
+ try {
6
+ return join(realpathSync.native(dirname(path)), basename(path));
7
+ }
8
+ catch (error) {
9
+ const code = error.code;
10
+ if (code === 'ENOENT' || code === 'ENOTDIR')
11
+ return resolve(path);
12
+ throw error;
13
+ }
14
+ }
@@ -6,7 +6,7 @@ export interface PoolLimitsAdapterOptions {
6
6
  readonly namespace: string;
7
7
  readonly store: PoolStore;
8
8
  readonly now?: () => number;
9
- /** Receives a warning when a detached envelope repair fails. */
9
+ /** Receives redacted replacement warnings and background envelope-loss repair failures. */
10
10
  readonly logger?: LimitsRecoveryLogger;
11
11
  }
12
12
  /**
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { PoolOperationError } from '../store/errors.js';
4
+ import { EnvelopeGuard } from './envelope.js';
4
5
  import { EnvelopeHistory, EnvelopeRepair, } from './envelope-loss.js';
5
6
  import { applyLimitsCommands, createLimitsNamespace, } from './namespace.js';
6
7
  import { LimitsPersistenceRefusal, } from './persistence.js';
@@ -20,34 +21,6 @@ function bindingsOf(namespace, rows) {
20
21
  },
21
22
  ]);
22
23
  }
23
- function decodeEnvelope(value, namespace, generation) {
24
- if (value === undefined)
25
- return createLimitsNamespace(namespace, generation);
26
- if (value === null ||
27
- typeof value !== 'object' ||
28
- !('schemaVersion' in value) ||
29
- value.schemaVersion !== 1 ||
30
- !('namespace' in value) ||
31
- value.namespace !== namespace ||
32
- !('generation' in value) ||
33
- typeof value.generation !== 'string' ||
34
- !('revision' in value) ||
35
- !Number.isSafeInteger(value.revision) ||
36
- value.revision < 0 ||
37
- !('lowWatermark' in value) ||
38
- !Number.isSafeInteger(value.lowWatermark) ||
39
- value.lowWatermark < 0 ||
40
- !('marks' in value) ||
41
- !Array.isArray(value.marks) ||
42
- !('tombstones' in value) ||
43
- !Array.isArray(value.tombstones) ||
44
- !('operationIds' in value) ||
45
- !Array.isArray(value.operationIds) ||
46
- !('access' in value) ||
47
- !Array.isArray(value.access))
48
- throw new TypeError('Invalid or unsupported pool limits namespace');
49
- return value;
50
- }
51
24
  /**
52
25
  * Activate after initialize/load reports ready. Reads never acquire a write
53
26
  * lock; recovery is detached and commits merge under the store locks.
@@ -58,7 +31,8 @@ export async function createPoolLimitsAdapter(options) {
58
31
  throw new LimitsPersistenceRefusal('limits-unsupported');
59
32
  const update = store.updateLimitsNamespace.bind(store);
60
33
  const generation = randomUUID();
61
- const history = new EnvelopeHistory();
34
+ let history = new EnvelopeHistory();
35
+ const guard = new EnvelopeGuard(namespace, options.logger);
62
36
  const repair = new EnvelopeRepair(options.logger);
63
37
  const now = options.now ?? Date.now;
64
38
  const readBindings = async () => {
@@ -74,12 +48,10 @@ export async function createPoolLimitsAdapter(options) {
74
48
  const settings = await store.readSettings();
75
49
  if (settings.status !== 'ready')
76
50
  throw new LimitsPersistenceRefusal('pool-not-ready');
77
- const envelope = settings.settings.commonAuthLimits;
78
- return envelope === undefined
79
- ? undefined
80
- : decodeEnvelope(envelope, namespace, generation);
51
+ return guard.decode(settings.settings.commonAuthLimits);
81
52
  };
82
53
  const read = async (previous) => {
54
+ guard.assertWritable();
83
55
  let bindings = await readBindings();
84
56
  let snapshot = await readEnvelope();
85
57
  let last;
@@ -93,22 +65,23 @@ export async function createPoolLimitsAdapter(options) {
93
65
  const stable = isDeepStrictEqual(bindings, checked) &&
94
66
  isDeepStrictEqual(snapshot, checkedSnapshot);
95
67
  last = {
96
- snapshot: snapshot ?? createLimitsNamespace(namespace, generation),
68
+ snapshot: snapshot.snapshot ?? createLimitsNamespace(namespace, generation),
97
69
  bindings,
98
70
  authoritative: stable,
99
71
  };
100
72
  if (stable) {
101
- if (history.lost(snapshot, previous)) {
73
+ if (!snapshot.replacement &&
74
+ history.lost(snapshot.snapshot, previous)) {
102
75
  repair.schedule(() => adapter.commit([], previous));
103
76
  return {
104
- snapshot: history.recover(snapshot, previous, namespace, now()),
77
+ snapshot: history.recover(snapshot.snapshot, previous, namespace, now()),
105
78
  bindings,
106
79
  authoritative: false,
107
80
  degradedAgreement: true,
108
81
  };
109
82
  }
110
- if (snapshot)
111
- history.remember(snapshot);
83
+ if (snapshot.snapshot)
84
+ history.remember(snapshot.snapshot);
112
85
  return last;
113
86
  }
114
87
  bindings = checked;
@@ -121,14 +94,22 @@ export async function createPoolLimitsAdapter(options) {
121
94
  read,
122
95
  subscribe: repair.subscribe,
123
96
  async commit(commands, previous) {
97
+ guard.assertWritable();
124
98
  let committed;
99
+ let replacement;
100
+ const onPublished = () => {
101
+ if (guard.didCommit(replacement) && committed) {
102
+ history = new EnvelopeHistory();
103
+ history.remember(committed.snapshot, previous);
104
+ }
105
+ };
125
106
  try {
126
107
  await update((envelope, rows) => {
127
108
  const bindings = bindingsOf(namespace, rows);
128
- const present = envelope === undefined
129
- ? undefined
130
- : decodeEnvelope(envelope, namespace, generation);
131
- const degradedAgreement = history.lost(present, previous);
109
+ const decoded = guard.decode(envelope);
110
+ const present = decoded.snapshot;
111
+ replacement = decoded.replacement;
112
+ const degradedAgreement = !replacement && history.lost(present, previous);
132
113
  const result = applyLimitsCommands(degradedAgreement
133
114
  ? history.recover(present, previous, namespace, now())
134
115
  : (present ?? createLimitsNamespace(namespace, generation)), commands, {
@@ -143,9 +124,14 @@ export async function createPoolLimitsAdapter(options) {
143
124
  degradedAgreement,
144
125
  };
145
126
  return result.snapshot;
127
+ }, {
128
+ beforePublish: () => guard.assertWritable(),
129
+ onPublished,
146
130
  });
147
131
  }
148
132
  catch (error) {
133
+ // Store operations wrap mutator failures; preserve the typed terminal refusal.
134
+ guard.assertWritable();
149
135
  if (error instanceof PoolOperationError &&
150
136
  (error.kind === 'pending-migration' || error.kind === 'load-error'))
151
137
  throw new LimitsPersistenceRefusal('pool-not-ready');
@@ -153,6 +139,7 @@ export async function createPoolLimitsAdapter(options) {
153
139
  }
154
140
  if (!committed)
155
141
  throw new Error('Pool limits mutator was not called');
142
+ onPublished();
156
143
  history.remember(committed.snapshot, previous);
157
144
  return committed;
158
145
  },
@@ -1,4 +1,5 @@
1
1
  import type { SessionActivityStore } from './activity.js';
2
+ import { type LimitsAbandonReason } from './envelope.js';
2
3
  import type { IdentityBinding } from './identity.js';
3
4
  import type { LimitMarkCause } from './marker.js';
4
5
  import type { LimitsCommand, LimitsNamespace } from './namespace.js';
@@ -20,6 +21,8 @@ export interface LimitsRegistryOptions {
20
21
  /** Access is provider-owned; the registry must not guess its stored shape. */
21
22
  readonly isAccessRestrictive: (state: unknown) => boolean;
22
23
  readonly onEvent?: (event: LimitsRegistryEvent) => void;
24
+ /** Release this owner and serve without tracking; do not reacquire this store in this process. */
25
+ readonly onAbandon?: (reason: LimitsAbandonReason) => void;
23
26
  readonly onRejected?: (command: LimitsCommand, outcome: LimitsPersistenceOutcome) => void;
24
27
  }
25
28
  export interface LimitsDispatchView {
@@ -28,6 +31,8 @@ export interface LimitsDispatchView {
28
31
  readonly blocked: boolean;
29
32
  }
30
33
  export interface LimitsRegistry {
34
+ /** Terminal loss of tracking, not a dispatch refusal. Disposal never flushes after abandonment. */
35
+ readonly abandoned: LimitsAbandonReason | undefined;
31
36
  readonly snapshot: LimitsNamespace;
32
37
  readonly lastReloadAt: number;
33
38
  readonly degradedAgreement: boolean;
@@ -1,7 +1,8 @@
1
1
  import { AsyncResource } from 'node:async_hooks';
2
2
  import { createSessionActivityStore } from './activity.js';
3
+ import { limitsEnvelopeAbandonReason, } from './envelope.js';
3
4
  import { isIdentityCompatible, retainVerifiedIdentity } from './identity.js';
4
- import { applyLimitsCommands, pruneLimitsNamespace } from './namespace.js';
5
+ import { applyLimitsCommands, createLimitsNamespace, pruneLimitsNamespace, } from './namespace.js';
5
6
  import { LimitsPersistenceRefusal } from './persistence.js';
6
7
  import { sameAccount } from './request-history.js';
7
8
  export const LIMITS_REGISTRY_KEY = Symbol.for('@cortexkit/common-auth/limits-registry/schema-v1');
@@ -65,6 +66,7 @@ class Runtime {
65
66
  lastReadAttempt = Number.NEGATIVE_INFINITY;
66
67
  generation = 0;
67
68
  degradedAgreement = false;
69
+ abandoned;
68
70
  lastFailure;
69
71
  dirty = true;
70
72
  live = false;
@@ -74,16 +76,48 @@ class Runtime {
74
76
  reading;
75
77
  writing;
76
78
  handoff = Promise.resolve();
79
+ resolveAbandonment;
80
+ abandonment = new Promise((resolve) => {
81
+ this.resolveAbandonment = resolve;
82
+ });
77
83
  constructor(options) {
78
84
  this.adapter = options.adapter;
79
85
  this.clock = options.clock ?? clock;
80
86
  this.restrictive = options.isAccessRestrictive;
81
87
  }
82
88
  fail(error) {
89
+ if (this.abandoned)
90
+ return;
91
+ const reason = limitsEnvelopeAbandonReason(error);
92
+ if (reason) {
93
+ this.abandoned = reason;
94
+ this.lastFailure = error;
95
+ this.live = false;
96
+ this.generation++;
97
+ this.cancelTimers();
98
+ this.unsubscribe?.();
99
+ this.unsubscribe = undefined;
100
+ this.journal.clear();
101
+ this.failed.clear();
102
+ this.restrictions.clear();
103
+ this.recoveryView = undefined;
104
+ this.resolveAbandonment();
105
+ for (const listener of this.listeners) {
106
+ try {
107
+ listener.onAbandon?.(reason);
108
+ }
109
+ catch {
110
+ // Owners cannot prevent terminal cleanup for other owners.
111
+ }
112
+ }
113
+ return;
114
+ }
83
115
  this.degradedAgreement = true;
84
116
  this.lastFailure = error;
85
117
  }
86
118
  reconcile(view) {
119
+ if (this.abandoned)
120
+ return false;
87
121
  if (view.snapshot.schemaVersion !== 1 ||
88
122
  view.snapshot.namespace !== this.adapter.namespace)
89
123
  throw new Error('limits-schema-mismatch');
@@ -168,11 +202,13 @@ class Runtime {
168
202
  });
169
203
  }
170
204
  async start(adapter) {
205
+ if (this.abandoned)
206
+ throw this.lastFailure;
171
207
  this.adapter = adapter;
172
208
  this.live = true;
173
209
  const generation = ++this.generation;
174
210
  await this.reload();
175
- if (!this.snapshot)
211
+ if (this.abandoned || !this.snapshot)
176
212
  throw this.lastFailure ?? new Error('limits-hydration-failed');
177
213
  this.unsubscribe = adapter.subscribe?.(() => {
178
214
  if (!this.live || this.generation !== generation)
@@ -186,6 +222,8 @@ class Runtime {
186
222
  this.schedulePublish(0);
187
223
  }
188
224
  reload() {
225
+ if (this.abandoned)
226
+ return Promise.resolve();
189
227
  if (this.reading)
190
228
  return this.reading;
191
229
  const started = this.clock.now();
@@ -217,6 +255,8 @@ class Runtime {
217
255
  return this.reading;
218
256
  }
219
257
  provisional() {
258
+ if (this.abandoned)
259
+ return createLimitsNamespace(this.adapter.namespace, this.snapshot?.generation ?? '');
220
260
  const snapshot = this.recoveryView?.snapshot ?? this.snapshot;
221
261
  const pending = [...this.journal.values()]
222
262
  .map((p) => p.command)
@@ -236,6 +276,8 @@ class Runtime {
236
276
  };
237
277
  }
238
278
  enqueue(command, event) {
279
+ if (this.abandoned)
280
+ return;
239
281
  if (command.binding.account.namespace !== this.adapter.namespace)
240
282
  throw new Error('wrong-namespace');
241
283
  const id = opId(command);
@@ -249,6 +291,8 @@ class Runtime {
249
291
  this.schedulePublish(hasControl ? 0 : RELOAD_MS);
250
292
  }
251
293
  flush() {
294
+ if (this.abandoned)
295
+ return this.writing ?? Promise.resolve();
252
296
  if (this.writing)
253
297
  return this.writing;
254
298
  if (!this.journal.size)
@@ -256,9 +300,11 @@ class Runtime {
256
300
  this.writing = detached
257
301
  .runInAsyncScope(async () => {
258
302
  let batch = [...this.journal.values()];
259
- while (batch.length) {
303
+ while (batch.length && !this.abandoned) {
260
304
  try {
261
305
  const result = await this.adapter.commit(batch.map((p) => p.command), this.snapshot);
306
+ if (this.abandoned)
307
+ return;
262
308
  this.reconcile(result);
263
309
  if (!result.authoritative)
264
310
  throw new Error('limits-unverifiable-commit');
@@ -270,6 +316,12 @@ class Runtime {
270
316
  }
271
317
  }
272
318
  catch (error) {
319
+ if (limitsEnvelopeAbandonReason(error)) {
320
+ this.fail(error);
321
+ return;
322
+ }
323
+ if (this.abandoned)
324
+ return;
273
325
  if (error instanceof LimitsPersistenceRefusal &&
274
326
  error.code === 'pool-not-ready') {
275
327
  for (const pending of batch)
@@ -353,13 +405,17 @@ class Runtime {
353
405
  }
354
406
  }
355
407
  async beforeDispatch(binding) {
408
+ if (this.abandoned)
409
+ return { snapshot: this.provisional(), blocked: false };
356
410
  this.touch();
357
411
  const controls = () => [...this.journal.values()].some((p) => p.command.type !== 'mark' &&
358
412
  sameAccount(p.command.binding.account, binding.account));
359
413
  if (controls())
360
- await this.flush();
414
+ await Promise.race([this.flush(), this.abandonment]);
361
415
  if (this.dirty || this.clock.now() - this.lastReloadAt >= RELOAD_MS)
362
- await this.reload();
416
+ await Promise.race([this.reload(), this.abandonment]);
417
+ if (this.abandoned)
418
+ return { snapshot: this.provisional(), blocked: false };
363
419
  const current = (this.recoveryView?.bindings ?? this.bindings).find((b) => sameAccount(b.account, binding.account));
364
420
  const snapshot = this.provisional();
365
421
  return {
@@ -393,6 +449,7 @@ export async function acquireLimitsRegistry(options) {
393
449
  }
394
450
  const state = runtime;
395
451
  const listener = {
452
+ onAbandon: options.onAbandon,
396
453
  onEvent: options.onEvent,
397
454
  onRejected: options.onRejected,
398
455
  };
@@ -419,6 +476,9 @@ export async function acquireLimitsRegistry(options) {
419
476
  throw new Error('limits-registry-disposed');
420
477
  };
421
478
  return {
479
+ get abandoned() {
480
+ return state.abandoned;
481
+ },
422
482
  get snapshot() {
423
483
  active();
424
484
  return state.provisional();
@@ -5,7 +5,7 @@ export interface VaultLimitsAdapterOptions {
5
5
  readonly namespace: string;
6
6
  readonly path: string;
7
7
  readonly now?: () => number;
8
- /** Receives a warning when a detached envelope repair fails. */
8
+ /** Receives redacted replacement warnings and background envelope-loss repair failures. */
9
9
  readonly logger?: LimitsRecoveryLogger;
10
10
  }
11
11
  /**
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { mutateVaultRoster, readVaultRoster, } from '../claustrum/roster.js';
3
+ import { EnvelopeGuard } from './envelope.js';
3
4
  import { EnvelopeHistory, EnvelopeRepair, } from './envelope-loss.js';
4
5
  import { applyLimitsCommands, createLimitsNamespace, } from './namespace.js';
5
6
  function bindingsOf(namespace, roster) {
@@ -17,34 +18,6 @@ function bindingsOf(namespace, roster) {
17
18
  : { identity: row.accountIdentity }),
18
19
  }));
19
20
  }
20
- function decodeEnvelope(value, namespace, generation) {
21
- if (value === undefined)
22
- return createLimitsNamespace(namespace, generation);
23
- if (value === null ||
24
- typeof value !== 'object' ||
25
- !('schemaVersion' in value) ||
26
- value.schemaVersion !== 1 ||
27
- !('namespace' in value) ||
28
- value.namespace !== namespace ||
29
- !('generation' in value) ||
30
- typeof value.generation !== 'string' ||
31
- !('revision' in value) ||
32
- !Number.isSafeInteger(value.revision) ||
33
- value.revision < 0 ||
34
- !('lowWatermark' in value) ||
35
- !Number.isSafeInteger(value.lowWatermark) ||
36
- value.lowWatermark < 0 ||
37
- !('marks' in value) ||
38
- !Array.isArray(value.marks) ||
39
- !('tombstones' in value) ||
40
- !Array.isArray(value.tombstones) ||
41
- !('operationIds' in value) ||
42
- !Array.isArray(value.operationIds) ||
43
- !('access' in value) ||
44
- !Array.isArray(value.access))
45
- throw new TypeError('Invalid or unsupported vault limits namespace');
46
- return value;
47
- }
48
21
  /**
49
22
  * Reads use one atomic roster snapshot. Commits re-read both limits and row
50
23
  * bindings under the roster's existing write lock, without accessing local
@@ -53,15 +26,15 @@ function decodeEnvelope(value, namespace, generation) {
53
26
  export async function createVaultLimitsAdapter(options) {
54
27
  const { namespace, path } = options;
55
28
  const generation = randomUUID();
56
- const history = new EnvelopeHistory();
29
+ let history = new EnvelopeHistory();
30
+ const guard = new EnvelopeGuard(namespace, options.logger);
57
31
  const repair = new EnvelopeRepair(options.logger);
58
32
  const now = options.now ?? Date.now;
59
33
  const read = async (previous) => {
34
+ guard.assertWritable();
60
35
  const roster = await readVaultRoster(path);
61
- const present = roster?.limits === undefined
62
- ? undefined
63
- : decodeEnvelope(roster.limits, namespace, generation);
64
- if (history.lost(present, previous)) {
36
+ const { snapshot: present, replacement } = guard.decode(roster?.limits);
37
+ if (!replacement && history.lost(present, previous)) {
65
38
  repair.schedule(() => adapter.commit([], previous));
66
39
  return {
67
40
  snapshot: history.recover(present, previous, namespace, now()),
@@ -83,12 +56,21 @@ export async function createVaultLimitsAdapter(options) {
83
56
  read,
84
57
  subscribe: repair.subscribe,
85
58
  commit: async (commands, previous) => {
59
+ guard.assertWritable();
60
+ let replacement;
61
+ let publishedSnapshot;
62
+ const onPublished = () => {
63
+ if (guard.didCommit(replacement) && publishedSnapshot) {
64
+ history = new EnvelopeHistory();
65
+ history.remember(publishedSnapshot, previous);
66
+ }
67
+ };
86
68
  const committed = await mutateVaultRoster(path, (current) => {
87
69
  const bindings = bindingsOf(namespace, current);
88
- const present = current?.limits === undefined
89
- ? undefined
90
- : decodeEnvelope(current.limits, namespace, generation);
91
- const degradedAgreement = history.lost(present, previous);
70
+ const decoded = guard.decode(current?.limits);
71
+ const present = decoded.snapshot;
72
+ replacement = decoded.replacement;
73
+ const degradedAgreement = !replacement && history.lost(present, previous);
92
74
  const result = applyLimitsCommands(degradedAgreement
93
75
  ? history.recover(present, previous, namespace, now())
94
76
  : (present ?? createLimitsNamespace(namespace, generation)), commands, {
@@ -96,6 +78,7 @@ export async function createVaultLimitsAdapter(options) {
96
78
  bindings,
97
79
  authorizeEpoch: (observed, authoritative) => observed.credentialEpoch === authoritative.credentialEpoch,
98
80
  });
81
+ publishedSnapshot = result.snapshot;
99
82
  return {
100
83
  next: {
101
84
  ...(current ?? {
@@ -113,7 +96,11 @@ export async function createVaultLimitsAdapter(options) {
113
96
  degradedAgreement,
114
97
  },
115
98
  };
99
+ }, {
100
+ beforePublish: async () => guard.assertWritable(),
101
+ onPublished,
116
102
  });
103
+ onPublished();
117
104
  history.remember(committed.snapshot, previous);
118
105
  return committed;
119
106
  },
@@ -77,6 +77,12 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
77
77
  await writeEnrollmentTokenFile(path, file);
78
78
  },
79
79
  });
80
+ await fence();
81
+ const initial = await manager.status();
82
+ if (initial.state === 'approved') {
83
+ printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
84
+ return;
85
+ }
80
86
  printLine(terminal, `Asking the vault to connect ${name}…`);
81
87
  const deadline = now() + ENROLLMENT_WAIT_MS;
82
88
  let printedRequest;
@@ -84,7 +90,6 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
84
90
  let reportedCode;
85
91
  let failedProposals = 0;
86
92
  for (;;) {
87
- await fence();
88
93
  const status = await manager.reconcile();
89
94
  if (status.state === 'approved') {
90
95
  printLine(terminal, `Connected ${host} to Claustrum.`);
@@ -135,6 +140,7 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
135
140
  if (remaining <= 0)
136
141
  break;
137
142
  await wait(Math.min(pause, remaining));
143
+ await fence();
138
144
  }
139
145
  if (printedRequest)
140
146
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -3,7 +3,7 @@ export type { PoolFailureKind, PoolFailurePhase, PoolOperation, } from './errors
3
3
  export { PoolOperationError, PoolReentryError } from './errors.js';
4
4
  export type { PoolLogger } from './hooks.js';
5
5
  export { countUnknownIdentityRows, DUPLICATE_IDENTITY_REASON, } from './identity.js';
6
- export type { PoolLimitsMutator, PoolLimitsRow } from './limits-namespace.js';
6
+ export type { PoolLimitsMutator, PoolLimitsRow, PoolLimitsWriteOptions, } from './limits-namespace.js';
7
7
  export type { HoldPoint, InitializeOutcome, WriteStep } from './mutate.js';
8
8
  export type { OpenPoolStoreOptions, PoolLoad, PoolStore, } from './pool.js';
9
9
  export { openPoolStore } from './pool.js';
@@ -3,5 +3,11 @@ import type { PoolRow } from './schema.js';
3
3
  /** Row IDs, credential epochs and identities only; mutators never receive credentials. */
4
4
  export type PoolLimitsRow = Pick<PoolRow, 'id' | 'credentialEpoch' | 'identity'>;
5
5
  export type PoolLimitsMutator = (envelope: unknown, rows: readonly PoolLimitsRow[]) => unknown | Promise<unknown>;
6
+ /** Publication bookkeeping runs under the same locks as the namespace merge. */
7
+ export interface PoolLimitsWriteOptions {
8
+ readonly beforePublish?: () => void;
9
+ /** Runs once publication happened, even if a later step fails. Must not throw. */
10
+ readonly onPublished?: () => void;
11
+ }
6
12
  /** A namespace merge and its check of current row bindings share one locked config snapshot. */
7
- export declare function updatePoolLimitsNamespace(rt: StoreRuntime, mutator: PoolLimitsMutator): Promise<void>;
13
+ export declare function updatePoolLimitsNamespace(rt: StoreRuntime, mutator: PoolLimitsMutator, options?: PoolLimitsWriteOptions): Promise<void>;
@@ -2,7 +2,7 @@ import { writeJsonAtomic } from '../fs/atomic-write.js';
2
2
  import { assertLimitsWriteAllowed, runInsideHook } from './hooks.js';
3
3
  import { notReadyError, readPool, runOperation } from './mutate.js';
4
4
  /** A namespace merge and its check of current row bindings share one locked config snapshot. */
5
- export async function updatePoolLimitsNamespace(rt, mutator) {
5
+ export async function updatePoolLimitsNamespace(rt, mutator, options = {}) {
6
6
  assertLimitsWriteAllowed();
7
7
  const { ctx } = rt;
8
8
  await runOperation(ctx, 'updateLimitsNamespace', undefined, undefined, async (locks, progress) => {
@@ -22,13 +22,25 @@ export async function updatePoolLimitsNamespace(rt, mutator) {
22
22
  operation: 'updateLimitsNamespace',
23
23
  rowId: undefined,
24
24
  };
25
- await writeJsonAtomic(ctx.configPath, config, {
26
- beforeRename: async () => {
27
- await ctx.onStep?.('before-config-write', info);
28
- await locks.assertAll();
29
- },
30
- });
25
+ try {
26
+ await writeJsonAtomic(ctx.configPath, config, {
27
+ beforeRename: async () => {
28
+ await ctx.onStep?.('before-config-write', info);
29
+ await locks.assertAll();
30
+ options.beforePublish?.();
31
+ },
32
+ });
33
+ }
34
+ catch (error) {
35
+ if (error &&
36
+ typeof error === 'object' &&
37
+ 'published' in error &&
38
+ error.published === true)
39
+ options.onPublished?.();
40
+ throw error;
41
+ }
31
42
  progress.writes++;
43
+ options.onPublished?.();
32
44
  await ctx.onStep?.('after-config-write', info);
33
45
  });
34
46
  }
@@ -202,7 +202,7 @@ export interface PoolStore {
202
202
  * onPersisted/onFailure hook or a pull, but not in a lock-held mutator.
203
203
  * Optional so existing structural implementations remain compatible.
204
204
  */
205
- updateLimitsNamespace?(mutator: PoolLimitsMutator): Promise<void>;
205
+ updateLimitsNamespace?(mutator: PoolLimitsMutator, options?: import('./limits-namespace.js').PoolLimitsWriteOptions): Promise<void>;
206
206
  /**
207
207
  * Records the identity a lookup found for the row's credential. Since
208
208
  * 0.3.1 it takes the credential epoch the lookup was issued for, and
@@ -127,7 +127,7 @@ export function openPoolStore(options) {
127
127
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
128
128
  readSettings: () => readPoolSettings(rt),
129
129
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
130
- updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
130
+ updateLimitsNamespace: (mutator, options) => updatePoolLimitsNamespace(rt, mutator, options),
131
131
  recordIdentity: (id, identity, attribution, callOptions) => recordRowIdentity(rt, id, identity, attribution, callOptions),
132
132
  refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
133
133
  recordQuota: record,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.37.0",
3
+ "version": "0.38.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": {
@@ -141,7 +141,7 @@
141
141
  "@opencode/plugin": ">=2.0.21",
142
142
  "@opentui/core": ">=0.4.5",
143
143
  "@opentui/solid": ">=0.4.5",
144
- "solid-js": "1.9.12"
144
+ "solid-js": ">=1.9.12 <2"
145
145
  },
146
146
  "peerDependenciesMeta": {
147
147
  "@opentui/core": {
@@ -165,7 +165,7 @@
165
165
  },
166
166
  "devDependencies": {
167
167
  "@biomejs/biome": "2.5.14",
168
- "@cortexkit/claustrum-client": "^0.14.0",
168
+ "@cortexkit/claustrum-client": "^0.15.0",
169
169
  "@cortexkit/subc-client": "0.22.2",
170
170
  "@earendil-works/pi-coding-agent": "1.0.4",
171
171
  "@opencode/plugin": "2.0.21",
@@ -178,7 +178,7 @@
178
178
  "lefthook": "2.1.14",
179
179
  "pi-coding-agent-086": "npm:@earendil-works/pi-coding-agent@0.86.1",
180
180
  "proper-lockfile": "4.1.2",
181
- "solid-js": "1.9.12",
181
+ "solid-js": "1.9.18",
182
182
  "typescript": "7.0.2"
183
183
  }
184
184
  }