@cortexkit/common-auth 0.32.1 → 0.34.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.
Files changed (111) hide show
  1. package/dist/claustrum/consumer.d.ts +12 -0
  2. package/dist/claustrum/consumer.js +36 -0
  3. package/dist/claustrum/custody.d.ts +16 -4
  4. package/dist/claustrum/custody.js +74 -9
  5. package/dist/claustrum/hub.d.ts +3 -2
  6. package/dist/claustrum/hub.js +8 -0
  7. package/dist/claustrum/index.d.ts +1 -0
  8. package/dist/claustrum/roster.d.ts +2 -0
  9. package/dist/claustrum/roster.js +2 -0
  10. package/dist/claustrum/usage.d.ts +41 -0
  11. package/dist/claustrum/usage.js +145 -0
  12. package/dist/commands/builtins.d.ts +5 -0
  13. package/dist/commands/builtins.js +38 -0
  14. package/dist/fs/private-files.d.ts +5 -0
  15. package/dist/fs/private-files.js +7 -0
  16. package/dist/fs/refresh-file-lock.js +144 -49
  17. package/dist/fs/with-lock.js +34 -10
  18. package/dist/limits/activity.d.ts +26 -0
  19. package/dist/limits/activity.js +52 -0
  20. package/dist/limits/axes.d.ts +63 -0
  21. package/dist/limits/axes.js +7 -0
  22. package/dist/limits/bridge.d.ts +4 -0
  23. package/dist/limits/bridge.js +10 -0
  24. package/dist/limits/decide.d.ts +141 -0
  25. package/dist/limits/decide.js +383 -0
  26. package/dist/limits/duration.d.ts +8 -0
  27. package/dist/limits/duration.js +20 -0
  28. package/dist/limits/envelope-loss.d.ts +29 -0
  29. package/dist/limits/envelope-loss.js +150 -0
  30. package/dist/limits/families.d.ts +57 -0
  31. package/dist/limits/families.js +143 -0
  32. package/dist/limits/header-classifier.d.ts +9 -0
  33. package/dist/limits/header-classifier.js +121 -0
  34. package/dist/limits/hold.d.ts +13 -0
  35. package/dist/limits/hold.js +25 -0
  36. package/dist/limits/identity.d.ts +14 -0
  37. package/dist/limits/identity.js +21 -0
  38. package/dist/limits/index.d.ts +44 -0
  39. package/dist/limits/index.js +25 -0
  40. package/dist/limits/jitter.d.ts +2 -0
  41. package/dist/limits/jitter.js +9 -0
  42. package/dist/limits/labels.d.ts +3 -0
  43. package/dist/limits/labels.js +11 -0
  44. package/dist/limits/marker.d.ts +64 -0
  45. package/dist/limits/marker.js +96 -0
  46. package/dist/limits/merge-laws.d.ts +14 -0
  47. package/dist/limits/merge-laws.js +31 -0
  48. package/dist/limits/namespace.d.ts +89 -0
  49. package/dist/limits/namespace.js +183 -0
  50. package/dist/limits/persistence.d.ts +33 -0
  51. package/dist/limits/persistence.js +9 -0
  52. package/dist/limits/pi-wait.d.ts +16 -0
  53. package/dist/limits/pi-wait.js +51 -0
  54. package/dist/limits/pool-adapter.d.ts +16 -0
  55. package/dist/limits/pool-adapter.js +162 -0
  56. package/dist/limits/presets.d.ts +11 -0
  57. package/dist/limits/presets.js +223 -0
  58. package/dist/limits/registry.d.ts +49 -0
  59. package/dist/limits/registry.js +471 -0
  60. package/dist/limits/request-history.d.ts +77 -0
  61. package/dist/limits/request-history.js +117 -0
  62. package/dist/limits/reset.d.ts +21 -0
  63. package/dist/limits/reset.js +44 -0
  64. package/dist/limits/routing-hold.d.ts +16 -0
  65. package/dist/limits/routing-hold.js +23 -0
  66. package/dist/limits/scope.d.ts +12 -0
  67. package/dist/limits/scope.js +10 -0
  68. package/dist/limits/signal.d.ts +41 -0
  69. package/dist/limits/signal.js +1 -0
  70. package/dist/limits/terminal.d.ts +52 -0
  71. package/dist/limits/terminal.js +133 -0
  72. package/dist/limits/vault-adapter.d.ts +16 -0
  73. package/dist/limits/vault-adapter.js +123 -0
  74. package/dist/limits/vault.d.ts +1 -0
  75. package/dist/limits/vault.js +1 -0
  76. package/dist/limits/wake.d.ts +21 -0
  77. package/dist/limits/wake.js +47 -0
  78. package/dist/limits/wording.d.ts +25 -0
  79. package/dist/limits/wording.js +114 -0
  80. package/dist/opencode2/index.d.ts +1 -1
  81. package/dist/opencode2/install.d.ts +2 -2
  82. package/dist/opencode2/install.js +161 -18
  83. package/dist/opencode2/types.d.ts +95 -9
  84. package/dist/quota/format.d.ts +9 -4
  85. package/dist/quota/format.js +45 -26
  86. package/dist/quota-sidebar/index.jsx +27 -19
  87. package/dist/routing/admission.d.ts +7 -2
  88. package/dist/routing/admission.js +17 -7
  89. package/dist/routing-accessor/handle.d.ts +1 -0
  90. package/dist/routing-accessor/handle.js +10 -0
  91. package/dist/routing-accessor/index.d.ts +18 -2
  92. package/dist/routing-accessor/index.js +21 -11
  93. package/dist/rpc/port-file.d.ts +12 -3
  94. package/dist/rpc/port-file.js +46 -4
  95. package/dist/store/attribution.js +3 -2
  96. package/dist/store/errors.d.ts +1 -1
  97. package/dist/store/hooks.d.ts +5 -1
  98. package/dist/store/hooks.js +20 -5
  99. package/dist/store/index.d.ts +1 -0
  100. package/dist/store/limits-namespace.d.ts +7 -0
  101. package/dist/store/limits-namespace.js +34 -0
  102. package/dist/store/pool.d.ts +10 -1
  103. package/dist/store/pool.js +2 -0
  104. package/dist/store/provider-state.js +5 -5
  105. package/dist/store/refresh.js +1 -1
  106. package/dist/store/schema.js +9 -4
  107. package/dist/store/settings.d.ts +2 -0
  108. package/dist/store/settings.js +11 -4
  109. package/package.json +10 -2
  110. package/src/quota/format.ts +56 -26
  111. package/src/quota-sidebar/index.tsx +56 -32
@@ -5,6 +5,11 @@ export interface PortFileEntry {
5
5
  pid: number;
6
6
  startedAt: number;
7
7
  }
8
+ interface PortFileClock {
9
+ /** Internal clock seams for deterministic boot-time checks. */
10
+ now?: () => number;
11
+ uptime?: () => number;
12
+ }
8
13
  export declare function createManagedRpcStateDirPredicate(directoryPrefix: string): (name: string) => boolean;
9
14
  export declare function isManagedRpcStateDir(name: string, directoryPrefix: string): boolean;
10
15
  export declare function getRpcDir(rpcRoot: string, directoryPrefix: string, projectDirectory: string): string;
@@ -18,8 +23,11 @@ export declare function writePortFile(dir: string, entry: {
18
23
  /** Test seam for forcing staging-name collisions; defaults to randomUUID. */
19
24
  stageName?: () => string;
20
25
  }): Promise<string>;
21
- export declare function sweepRpcState(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log?: RpcLogChannel): Promise<void>;
22
- export interface DiscoverPortFileOptions {
26
+ export declare function sweepRpcState(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log?: RpcLogChannel, options?: PortFileClock & {
27
+ /** Internal seam for replacing a stale record before its identity recheck. */
28
+ beforeRemove?: (path: string) => void | Promise<void>;
29
+ }): Promise<void>;
30
+ export interface DiscoverPortFileOptions extends PortFileClock {
23
31
  /**
24
32
  * Return only the expected PID's entry, or null; never fall back to
25
33
  * another live server. Without an expected PID nothing matches, so the
@@ -29,5 +37,6 @@ export interface DiscoverPortFileOptions {
29
37
  exactPid?: boolean;
30
38
  }
31
39
  /** Internal cache validation: probe only the selected file and its PID. */
32
- export declare function portFileIdentity(dir: string, entry: PortFileEntry): Promise<string | null>;
40
+ export declare function portFileIdentity(dir: string, entry: PortFileEntry, options?: PortFileClock): Promise<string | null>;
33
41
  export declare function discoverPortFile(dir: string, expectedPid?: number, options?: DiscoverPortFileOptions): Promise<PortFileEntry | null>;
42
+ export {};
@@ -1,7 +1,36 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { chmod, mkdir, open, readdir, rename, rmdir, stat, unlink, } from 'node:fs/promises';
3
+ import { uptime } from 'node:os';
3
4
  import { join, resolve } from 'node:path';
4
5
  import { ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
6
+ function staleBefore(clock) {
7
+ // A five-minute margin favors keeping a live record when clocks are uncertain.
8
+ return (clock.now ?? Date.now)() - (clock.uptime ?? uptime)() * 1000 - 300_000;
9
+ }
10
+ function isStalePortFile(entry, info, cutoff) {
11
+ const time = entry.startedAt === undefined ? info?.mtimeMs : entry.startedAt;
12
+ return typeof time === 'number' && Number.isFinite(time) && time < cutoff;
13
+ }
14
+ async function removeStalePortFile(path, raw, info, beforeRemove) {
15
+ if (!info)
16
+ return;
17
+ await beforeRemove?.(path);
18
+ try {
19
+ // A live PID may have replaced its old record while the sweep was reading it.
20
+ const current = await readPrivateText(path);
21
+ const identity = await stat(path);
22
+ if (current === raw &&
23
+ identity.dev === info.dev &&
24
+ identity.ino === info.ino &&
25
+ identity.mtimeMs === info.mtimeMs &&
26
+ identity.size === info.size)
27
+ await unlink(path).catch(() => { });
28
+ }
29
+ catch (error) {
30
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
31
+ throw error;
32
+ }
33
+ }
5
34
  /**
6
35
  * A PID a liveness probe may address. `process.kill(0 | negative, 0)` signals
7
36
  * a process group rather than a process, and an unsafe integer cannot name a
@@ -117,7 +146,8 @@ export async function writePortFile(dir, entry, options = {}) {
117
146
  throw error;
118
147
  }
119
148
  }
120
- export async function sweepRpcState(root, activeDir, isManagedDir, log) {
149
+ export async function sweepRpcState(root, activeDir, isManagedDir, log, options = {}) {
150
+ const cutoff = staleBefore(options);
121
151
  let projectDirs;
122
152
  try {
123
153
  projectDirs = await readdir(root, { withFileTypes: true });
@@ -146,6 +176,7 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
146
176
  if (!name.startsWith('port-') || !name.endsWith('.json'))
147
177
  continue;
148
178
  const portFile = join(dir, name);
179
+ const info = await stat(portFile).catch(() => undefined);
149
180
  let raw;
150
181
  try {
151
182
  raw = await readPrivateText(portFile);
@@ -172,13 +203,16 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
172
203
  const entry = parsed;
173
204
  if (!pidAlive(entry.pid))
174
205
  await unlink(portFile).catch(() => { });
206
+ else if (isStalePortFile(entry, info, cutoff))
207
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
175
208
  }
176
209
  if (resolve(dir) !== active)
177
210
  await rmdir(dir).catch(() => { });
178
211
  }
179
212
  }
180
213
  /** Internal cache validation: probe only the selected file and its PID. */
181
- export async function portFileIdentity(dir, entry) {
214
+ export async function portFileIdentity(dir, entry, options = {}) {
215
+ const cutoff = staleBefore(options);
182
216
  if (!pidAlive(entry.pid))
183
217
  return null;
184
218
  const path = join(resolve(dir), `port-${entry.pid}.json`);
@@ -186,6 +220,8 @@ export async function portFileIdentity(dir, entry) {
186
220
  if (windowsPrivateFiles)
187
221
  await verifyPrivate(path, 'file');
188
222
  const info = await stat(path);
223
+ if (isStalePortFile(entry, info, cutoff))
224
+ return null;
189
225
  return `${path}:${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
190
226
  }
191
227
  catch (error) {
@@ -195,6 +231,7 @@ export async function portFileIdentity(dir, entry) {
195
231
  }
196
232
  }
197
233
  export async function discoverPortFile(dir, expectedPid, options = {}) {
234
+ const cutoff = staleBefore(options);
198
235
  let names;
199
236
  try {
200
237
  if (windowsPrivateFiles)
@@ -213,8 +250,13 @@ export async function discoverPortFile(dir, expectedPid, options = {}) {
213
250
  try {
214
251
  const parsed = JSON.parse(await readPrivateText(join(dir, name)));
215
252
  if (isUsablePortFileEntry(parsed, name)) {
216
- if (pidAlive(parsed.pid))
217
- live.push(parsed);
253
+ if (pidAlive(parsed.pid)) {
254
+ const info = parsed.startedAt === undefined
255
+ ? await stat(join(dir, name)).catch(() => undefined)
256
+ : undefined;
257
+ if (!isStalePortFile(parsed, info, cutoff))
258
+ live.push(parsed);
259
+ }
218
260
  else
219
261
  await unlink(join(dir, name)).catch(() => { });
220
262
  }
@@ -1,4 +1,5 @@
1
1
  import { PoolOperationError } from './errors.js';
2
+ import { runInsideCodec } from './hooks.js';
2
3
  import { toFailure, withTransaction, } from './mutate.js';
3
4
  import { LockStack } from './refresh-lock.js';
4
5
  import { refusal, requireBound, unknownRow, } from './runtime.js';
@@ -31,8 +32,8 @@ export function assertQuotaRow(id, attribution, row) {
31
32
  });
32
33
  }
33
34
  export function mergedQuota(ctx, id, stored, observation) {
34
- const merged = ctx.codec.merge(stored, observation);
35
- if (!ctx.codec.validate(merged))
35
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
36
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
36
37
  throw refusal('pull', id, 'invalid-quota', 'the quota codec rejected the merged map');
37
38
  return merged;
38
39
  }
@@ -1,6 +1,6 @@
1
1
  import type { StoredCredential } from './schema.js';
2
2
  /** Every library operation that can fail, as named in the failure value. */
3
- export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
3
+ export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'updateLimitsNamespace' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
4
4
  /**
5
5
  * How far an operation got before it failed.
6
6
  *
@@ -1,7 +1,11 @@
1
1
  import { type PoolOperation } from './errors.js';
2
2
  /** Refuses a row operation or refresh called from inside a hook. */
3
3
  export declare function assertNotInsideHook(operation: PoolOperation): void;
4
- export declare function runInsideHook<T>(operation: PoolOperation, fn: () => Promise<T> | T): Promise<T>;
4
+ /** Namespace writes need only the store locks, not the row lock a hook may retain. */
5
+ export declare function assertLimitsWriteAllowed(): void;
6
+ /** Codecs may run under store locks even when no asynchronous hook is active. */
7
+ export declare function runInsideCodec<T>(fn: () => T): T;
8
+ export declare function runInsideHook<T>(operation: PoolOperation, fn: () => Promise<T> | T, storeLocksReleased?: boolean): Promise<T>;
5
9
  export interface PoolLogger {
6
10
  warn(message: string, data?: unknown): void;
7
11
  }
@@ -1,18 +1,33 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { PoolReentryError } from './errors.js';
3
3
  /**
4
- * Set while a hook of a lock-holding operation runs. Async context is
5
- * inherited by every timer, promise and continuation created inside the hook,
4
+ * Set while a store hook runs, recording whether its store locks are released.
5
+ * Async context is inherited by every timer, promise and continuation inside the hook,
6
6
  * so work a hook schedules is inside the guarded region too.
7
7
  */
8
8
  const insideHook = new AsyncLocalStorage();
9
+ const insideCodec = new AsyncLocalStorage();
9
10
  /** Refuses a row operation or refresh called from inside a hook. */
10
11
  export function assertNotInsideHook(operation) {
11
12
  if (insideHook.getStore() !== undefined)
12
13
  throw new PoolReentryError(operation);
13
14
  }
14
- export function runInsideHook(operation, fn) {
15
- return insideHook.run(operation, async () => await fn());
15
+ /** Namespace writes need only the store locks, not the row lock a hook may retain. */
16
+ export function assertLimitsWriteAllowed() {
17
+ if (insideHook.getStore()?.storeLocksReleased === false ||
18
+ insideCodec.getStore())
19
+ throw new PoolReentryError('updateLimitsNamespace');
20
+ }
21
+ /** Codecs may run under store locks even when no asynchronous hook is active. */
22
+ export function runInsideCodec(fn) {
23
+ return insideCodec.run(true, fn);
24
+ }
25
+ export function runInsideHook(operation, fn, storeLocksReleased = false) {
26
+ return insideHook.run({
27
+ operation,
28
+ storeLocksReleased: storeLocksReleased &&
29
+ insideHook.getStore()?.storeLocksReleased !== false,
30
+ }, async () => await fn());
16
31
  }
17
32
  /**
18
33
  * Runs a failure hook. A hook that throws never replaces the failure it was
@@ -22,7 +37,7 @@ export async function callFailureHook(operation, hook, rowId, error, logger) {
22
37
  if (!hook)
23
38
  return;
24
39
  try {
25
- await runInsideHook(operation, () => hook(rowId, error));
40
+ await runInsideHook(operation, () => hook(rowId, error), true);
26
41
  }
27
42
  catch (hookError) {
28
43
  logger?.warn('store failure hook threw; the original failure stands', {
@@ -3,6 +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
7
  export type { HoldPoint, InitializeOutcome, WriteStep } from './mutate.js';
7
8
  export type { OpenPoolStoreOptions, PoolLoad, PoolStore, } from './pool.js';
8
9
  export { openPoolStore } from './pool.js';
@@ -0,0 +1,7 @@
1
+ import type { StoreRuntime } from './runtime.js';
2
+ import type { PoolRow } from './schema.js';
3
+ /** Row IDs, credential epochs and identities only; mutators never receive credentials. */
4
+ export type PoolLimitsRow = Pick<PoolRow, 'id' | 'credentialEpoch' | 'identity'>;
5
+ export type PoolLimitsMutator = (envelope: unknown, rows: readonly PoolLimitsRow[]) => unknown | Promise<unknown>;
6
+ /** 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>;
@@ -0,0 +1,34 @@
1
+ import { writeJsonAtomic } from '../fs/atomic-write.js';
2
+ import { assertLimitsWriteAllowed, runInsideHook } from './hooks.js';
3
+ import { notReadyError, readPool, runOperation } from './mutate.js';
4
+ /** A namespace merge and its check of current row bindings share one locked config snapshot. */
5
+ export async function updatePoolLimitsNamespace(rt, mutator) {
6
+ assertLimitsWriteAllowed();
7
+ const { ctx } = rt;
8
+ await runOperation(ctx, 'updateLimitsNamespace', undefined, undefined, async (locks, progress) => {
9
+ for (const spec of ctx.storeLocks)
10
+ await locks.acquire(spec);
11
+ const result = await readPool(ctx);
12
+ if (result.status !== 'ready')
13
+ throw notReadyError(result, 'updateLimitsNamespace', undefined);
14
+ const rows = result.rows.map(({ id, credentialEpoch, identity }) => ({
15
+ id,
16
+ credentialEpoch,
17
+ identity,
18
+ }));
19
+ const envelope = await runInsideHook('updateLimitsNamespace', () => mutator(structuredClone(result.config.commonAuthLimits), rows));
20
+ const config = { ...result.config, commonAuthLimits: envelope };
21
+ const info = {
22
+ operation: 'updateLimitsNamespace',
23
+ rowId: undefined,
24
+ };
25
+ await writeJsonAtomic(ctx.configPath, config, {
26
+ beforeRename: async () => {
27
+ await ctx.onStep?.('before-config-write', info);
28
+ await locks.assertAll();
29
+ },
30
+ });
31
+ progress.writes++;
32
+ await ctx.onStep?.('after-config-write', info);
33
+ });
34
+ }
@@ -2,6 +2,7 @@ import type { QuotaCommitTimer } from '../quota/commit-interval.js';
2
2
  import { type Attribution } from './attribution.js';
3
3
  import type { PoolOperationError } from './errors.js';
4
4
  import type { PoolLogger } from './hooks.js';
5
+ import { type PoolLimitsMutator } from './limits-namespace.js';
5
6
  import { type HoldPoint, type InitializeOutcome, type StoreContext } from './mutate.js';
6
7
  import { type ProviderStateMutator, type UpdateProviderStateResult } from './provider-state.js';
7
8
  import { type PublicationReceipt, type PublishOptions, type PublishPlan, type PublishResult } from './publication.js';
@@ -191,9 +192,17 @@ export interface PoolStore {
191
192
  /**
192
193
  * One locked write of the plugin's settings (since 0.2.6) beside the pool,
193
194
  * in the config file. Refuses a result that sets a pool-owned key
194
- * (`invalid-input`). Takes `extraLocks`, then the store locks.
195
+ * (`invalid-input`). Carries commonAuthLimits through unchanged and refuses
196
+ * an explicit alteration to it. Takes `extraLocks`, then the store locks.
195
197
  */
196
198
  updateSettings(mutator: SettingsMutator, options?: UpdateSettingsOptions): Promise<UpdateSettingsResult>;
199
+ /**
200
+ * Merges commonAuthLimits with current row bindings in one config write.
201
+ * Requires a ready pool and takes only the store locks. May run in an
202
+ * onPersisted/onFailure hook or a pull, but not in a lock-held mutator.
203
+ * Optional so existing structural implementations remain compatible.
204
+ */
205
+ updateLimitsNamespace?(mutator: PoolLimitsMutator): Promise<void>;
197
206
  /**
198
207
  * Records the identity a lookup found for the row's credential. Since
199
208
  * 0.3.1 it takes the credential epoch the lookup was issued for, and
@@ -1,4 +1,5 @@
1
1
  import { recordQuota } from './attribution.js';
2
+ import { updatePoolLimitsNamespace, } from './limits-namespace.js';
2
3
  import { initializePool, readPool, } from './mutate.js';
3
4
  import { updateProviderStateRow, } from './provider-state.js';
4
5
  import { publication, publishRoster, } from './publication.js';
@@ -126,6 +127,7 @@ export function openPoolStore(options) {
126
127
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
127
128
  readSettings: () => readPoolSettings(rt),
128
129
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
130
+ updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
129
131
  recordIdentity: (id, identity, attribution, callOptions) => recordRowIdentity(rt, id, identity, attribution, callOptions),
130
132
  refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
131
133
  recordQuota: record,
@@ -1,4 +1,4 @@
1
- import { assertNotInsideHook, runInsideHook } from './hooks.js';
1
+ import { assertNotInsideHook, runInsideCodec, runInsideHook } from './hooks.js';
2
2
  import { runOperation, withTransaction } from './mutate.js';
3
3
  import { readRow, refusal, requireBound, rowLockSpec, unknownRow, } from './runtime.js';
4
4
  import { boundProviderStateDigest, CREDENTIAL_STAMP_KEY, credentialDigest, isCredentialEpoch, isRecord, PROVIDER_STATE_KEY, parseStamp, providerStateDigest, rowLockKey, } from './schema.js';
@@ -21,7 +21,7 @@ export function acceptProviderState(codec, operation, id, value, what = 'the pro
21
21
  }
22
22
  if (normalized === undefined)
23
23
  throw refusal(operation, id, 'invalid-provider-state', `${what} cannot be stored as JSON`);
24
- if (!codec.validate(normalized))
24
+ if (!runInsideCodec(() => codec.validate(normalized)))
25
25
  throw refusal(operation, id, 'invalid-provider-state', `the provider-state codec rejected ${what}`);
26
26
  return normalized;
27
27
  }
@@ -35,7 +35,7 @@ export function mergedProviderState(codec, operation, id, onDisk, incoming) {
35
35
  return { kind: 'set', value: incoming };
36
36
  return {
37
37
  kind: 'set',
38
- value: acceptProviderState(codec, operation, id, codec.merge(structuredClone(onDisk), structuredClone(incoming)), 'the merged provider state'),
38
+ value: acceptProviderState(codec, operation, id, runInsideCodec(() => codec.merge?.(structuredClone(onDisk), structuredClone(incoming))), 'the merged provider state'),
39
39
  };
40
40
  }
41
41
  /**
@@ -48,7 +48,7 @@ export function mergedProviderState(codec, operation, id, onDisk, incoming) {
48
48
  export function replacementProviderState(codec, row, credentialEpoch, identity, incoming) {
49
49
  const hook = codec?.onReplace;
50
50
  const next = hook
51
- ? hook(row.providerState === undefined
51
+ ? runInsideCodec(() => hook(row.providerState === undefined
52
52
  ? undefined
53
53
  : structuredClone(row.providerState), {
54
54
  id: row.id,
@@ -60,7 +60,7 @@ export function replacementProviderState(codec, row, credentialEpoch, identity,
60
60
  ...(incoming !== undefined
61
61
  ? { incoming: structuredClone(incoming) }
62
62
  : {}),
63
- })
63
+ }))
64
64
  : incoming;
65
65
  if (next === undefined)
66
66
  return { kind: 'clear' };
@@ -200,7 +200,7 @@ export async function refreshRow(rt, id, provider, options = {}) {
200
200
  if (options.onPersisted) {
201
201
  try {
202
202
  const persisted = options.onPersisted;
203
- await runInsideHook('refresh', () => persisted(id, commit.stored));
203
+ await runInsideHook('refresh', () => persisted(id, commit.stored), true);
204
204
  }
205
205
  catch (cause) {
206
206
  throw new PoolOperationError({
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { runInsideCodec } from './hooks.js';
2
3
  /** Top-level key of the config file that holds everything the pool adds. */
3
4
  export const POOL_KEY = 'commonAuthPool';
4
5
  /** The pool schema this library reads and writes. */
@@ -182,7 +183,9 @@ export function stampFor(credential, credentialEpoch, binding, options = {}) {
182
183
  * digest the store writes.
183
184
  */
184
185
  export function providerStateDigest(codec, value) {
185
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
186
+ const bound = codec?.credentialBound
187
+ ? runInsideCodec(() => codec.credentialBound?.(value))
188
+ : value;
186
189
  return createHash('sha256')
187
190
  .update(`provider-state\0${JSON.stringify(bound ?? null)}`)
188
191
  .digest('hex');
@@ -420,8 +423,10 @@ function parseEntry(raw, codec) {
420
423
  return undefined;
421
424
  if ('disabledReason' in raw && typeof raw.disabledReason !== 'string')
422
425
  return undefined;
423
- const quota = 'quota' in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
424
- if ('quota' in raw && !codec.validate(quota))
426
+ const quota = 'quota' in raw && codec.decode
427
+ ? runInsideCodec(() => codec.decode?.(raw.quota))
428
+ : raw.quota;
429
+ if ('quota' in raw && !runInsideCodec(() => codec.validate(quota)))
425
430
  return undefined;
426
431
  if ('staged' in raw && !parseReservation(raw.staged))
427
432
  return undefined;
@@ -666,7 +671,7 @@ function providerStateFields(account, credential, credentialEpoch, identity, cod
666
671
  const value = account[PROVIDER_STATE_KEY];
667
672
  // The value is validated before it is projected, so the projection only
668
673
  // ever sees a value of the shape the codec accepts.
669
- if (!codec?.validate(value))
674
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
670
675
  return { providerStateDropped: 'invalid' };
671
676
  if (providerStateDigest(codec, value) !== digest)
672
677
  return { providerStateDropped: 'uncovered' };
@@ -59,5 +59,7 @@ export declare function readPoolSettings(rt: StoreRuntime): Promise<SettingsRead
59
59
  * pool-owned key refuses (`invalid-input`) with nothing written; a result
60
60
  * equal to the current settings writes nothing. The state file is never
61
61
  * touched, and the pool-owned keys are written back exactly as read.
62
+ * commonAuthLimits is also carried through unchanged, even when omitted by
63
+ * the mutator; an explicit change to it refuses before writing anything.
62
64
  */
63
65
  export declare function updatePoolSettings(rt: StoreRuntime, mutator: SettingsMutator, options?: UpdateSettingsOptions): Promise<UpdateSettingsResult>;
@@ -36,12 +36,13 @@ function defineKey(target, key, value) {
36
36
  /**
37
37
  * The next config: the pool-owned keys exactly as read, every settings key
38
38
  * from `next` in its existing position, settings keys `next` dropped left
39
- * out, and new settings keys appended.
39
+ * out, and new settings keys appended. The limits envelope is always carried
40
+ * through from disk; ordinary settings mutators do not own that namespace.
40
41
  */
41
42
  function composeConfig(config, next) {
42
43
  const out = {};
43
44
  for (const [key, value] of Object.entries(config)) {
44
- if (POOL_OWNED_KEYS.includes(key))
45
+ if (POOL_OWNED_KEYS.includes(key) || key === 'commonAuthLimits')
45
46
  defineKey(out, key, value);
46
47
  else if (Object.hasOwn(next, key))
47
48
  defineKey(out, key, next[key]);
@@ -82,6 +83,8 @@ export async function readPoolSettings(rt) {
82
83
  * pool-owned key refuses (`invalid-input`) with nothing written; a result
83
84
  * equal to the current settings writes nothing. The state file is never
84
85
  * touched, and the pool-owned keys are written back exactly as read.
86
+ * commonAuthLimits is also carried through unchanged, even when omitted by
87
+ * the mutator; an explicit change to it refuses before writing anything.
85
88
  */
86
89
  export async function updatePoolSettings(rt, mutator, options = {}) {
87
90
  assertNotInsideHook('updateSettings');
@@ -109,9 +112,13 @@ export async function updatePoolSettings(rt, mutator, options = {}) {
109
112
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
110
113
  if (owned.length > 0)
111
114
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(', ')}`);
112
- if (isDeepStrictEqual(next, current))
113
- return { settings: current, outcome: 'unchanged' };
115
+ if (Object.hasOwn(next, 'commonAuthLimits') &&
116
+ (!Object.hasOwn(current, 'commonAuthLimits') ||
117
+ !isDeepStrictEqual(next.commonAuthLimits, current.commonAuthLimits)))
118
+ throw settingsRefusal('settings cannot alter commonAuthLimits; use updateLimitsNamespace');
114
119
  const config = composeConfig(result.config, next);
120
+ if (isDeepStrictEqual(settingsOf(config), current))
121
+ return { settings: current, outcome: 'unchanged' };
115
122
  const info = { operation: 'updateSettings', rowId: undefined };
116
123
  await writeJsonAtomic(ctx.configPath, config, {
117
124
  beforeRename: async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.32.1",
3
+ "version": "0.34.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": {
@@ -68,6 +68,14 @@
68
68
  "types": "./dist/quota/index.d.ts",
69
69
  "import": "./dist/quota/index.js"
70
70
  },
71
+ "./limits": {
72
+ "types": "./dist/limits/index.d.ts",
73
+ "import": "./dist/limits/index.js"
74
+ },
75
+ "./limits/vault": {
76
+ "types": "./dist/limits/vault.d.ts",
77
+ "import": "./dist/limits/vault.js"
78
+ },
71
79
  "./routing": {
72
80
  "types": "./dist/routing/index.d.ts",
73
81
  "import": "./dist/routing/index.js"
@@ -157,7 +165,7 @@
157
165
  },
158
166
  "devDependencies": {
159
167
  "@biomejs/biome": "2.5.14",
160
- "@cortexkit/claustrum-client": "^0.13.0",
168
+ "@cortexkit/claustrum-client": "^0.14.0",
161
169
  "@cortexkit/subc-client": "0.22.2",
162
170
  "@earendil-works/pi-coding-agent": "1.0.4",
163
171
  "@opencode/plugin": "2.0.21",