@cortexkit/common-auth 0.19.0 → 0.20.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.
@@ -0,0 +1,89 @@
1
+ import { ClaustrumConsumerError } from './errors.js';
2
+ export type VaultFailureClass = 'unreachable' | 'answered';
3
+ /**
4
+ * Codes from claustrum-client's decoder and its subc transport. A retry action
5
+ * alone is not evidence of an outage: even transient vault refusals must win
6
+ * over a previously served credential. New codes fail closed until reviewed.
7
+ */
8
+ export declare const VAULT_FAILURE_CLASSES: Readonly<{
9
+ ECONNREFUSED: "unreachable";
10
+ ENOENT: "unreachable";
11
+ ECONNRESET: "unreachable";
12
+ EPIPE: "unreachable";
13
+ ETIMEDOUT: "unreachable";
14
+ transport_error: "unreachable";
15
+ unavailable: "unreachable";
16
+ timeout: "unreachable";
17
+ route_closed: "unreachable";
18
+ daemon_draining: "unreachable";
19
+ connection_closed: "unreachable";
20
+ connection_dropped: "unreachable";
21
+ request_deadline: "unreachable";
22
+ deadline_exceeded_no_drop_observed: "unreachable";
23
+ module_reloading: "unreachable";
24
+ module_warming: "unreachable";
25
+ target_unavailable: "unreachable";
26
+ module_timeout: "unreachable";
27
+ invalid_response: "answered";
28
+ invalid_record_version: "answered";
29
+ invalid_expiry: "answered";
30
+ invalid_status: "answered";
31
+ invalid_params: "answered";
32
+ ttl_unsatisfiable: "answered";
33
+ not_found: "answered";
34
+ enrollment_revoked: "answered";
35
+ enrollment_invalid: "answered";
36
+ grant_denied: "answered";
37
+ credential_unavailable: "answered";
38
+ needs_reauth: "answered";
39
+ declined: "answered";
40
+ disabled: "answered";
41
+ identity_changed: "answered";
42
+ closed: "answered";
43
+ client_closed: "answered";
44
+ pending_exists: "answered";
45
+ pending_queue_full: "answered";
46
+ already_consumed: "answered";
47
+ superseded: "answered";
48
+ stale_generation: "answered";
49
+ missing_identity: "answered";
50
+ invalid_control_body: "answered";
51
+ unknown_module: "answered";
52
+ module_removed: "answered";
53
+ capability_denied: "answered";
54
+ unknown_channel: "unreachable";
55
+ stale_route_epoch: "unreachable";
56
+ capability_forbidden: "answered";
57
+ capability_unprovided: "answered";
58
+ capability_ambiguous: "answered";
59
+ invalid_capability_identifier: "answered";
60
+ binary_body_required: "answered";
61
+ binary_call_requires_call_binary: "answered";
62
+ corr_exhausted: "answered";
63
+ late_route_cleanup_failed: "answered";
64
+ reverse_request_capability_not_declared: "answered";
65
+ stale_route_handle: "answered";
66
+ reverse_request_unhandled: "answered";
67
+ handler_error: "answered";
68
+ health_error: "answered";
69
+ duplicate_module_id: "answered";
70
+ route_rejected: "answered";
71
+ lock_busy: "answered";
72
+ owner_invalid: "answered";
73
+ renewal_failed: "answered";
74
+ unsupported_platform: "answered";
75
+ EACCES: "answered";
76
+ EPERM: "answered";
77
+ ERR_PRIVATE_FILES_SECURITY: "answered";
78
+ }>;
79
+ /**
80
+ * An injected adapter may throw this ONLY when its connection/transport is
81
+ * unreachable, including a failed connect before getScoped. Do not wrap an
82
+ * adapter shutdown, cancellation, validation error or vault refusal in it.
83
+ * Its fixed message cannot echo enrollment or credential material, and its
84
+ * kind stays `unavailable` for callers handling ClaustrumConsumerError.
85
+ */
86
+ export declare class ClaustrumUnreachableError extends ClaustrumConsumerError {
87
+ constructor();
88
+ }
89
+ export declare function classifyVaultFailure(error: unknown): VaultFailureClass;
@@ -0,0 +1,106 @@
1
+ import { ClaustrumCredentialError } from '@cortexkit/claustrum-client';
2
+ import { SocketClosedError, SocketTimeoutError, SubcCallError, } from '@cortexkit/subc-client';
3
+ import { ClaustrumConsumerError } from './errors.js';
4
+ /**
5
+ * Codes from claustrum-client's decoder and its subc transport. A retry action
6
+ * alone is not evidence of an outage: even transient vault refusals must win
7
+ * over a previously served credential. New codes fail closed until reviewed.
8
+ */
9
+ export const VAULT_FAILURE_CLASSES = Object.freeze({
10
+ ECONNREFUSED: 'unreachable',
11
+ ENOENT: 'unreachable',
12
+ ECONNRESET: 'unreachable',
13
+ EPIPE: 'unreachable',
14
+ ETIMEDOUT: 'unreachable',
15
+ transport_error: 'unreachable',
16
+ unavailable: 'unreachable',
17
+ timeout: 'unreachable',
18
+ route_closed: 'unreachable',
19
+ daemon_draining: 'unreachable',
20
+ connection_closed: 'unreachable',
21
+ connection_dropped: 'unreachable',
22
+ request_deadline: 'unreachable',
23
+ deadline_exceeded_no_drop_observed: 'unreachable',
24
+ module_reloading: 'unreachable',
25
+ module_warming: 'unreachable',
26
+ target_unavailable: 'unreachable',
27
+ module_timeout: 'unreachable',
28
+ invalid_response: 'answered',
29
+ invalid_record_version: 'answered',
30
+ invalid_expiry: 'answered',
31
+ invalid_status: 'answered',
32
+ invalid_params: 'answered',
33
+ ttl_unsatisfiable: 'answered',
34
+ not_found: 'answered',
35
+ enrollment_revoked: 'answered',
36
+ enrollment_invalid: 'answered',
37
+ grant_denied: 'answered',
38
+ credential_unavailable: 'answered',
39
+ needs_reauth: 'answered',
40
+ declined: 'answered',
41
+ disabled: 'answered',
42
+ identity_changed: 'answered',
43
+ closed: 'answered',
44
+ client_closed: 'answered',
45
+ pending_exists: 'answered',
46
+ pending_queue_full: 'answered',
47
+ already_consumed: 'answered',
48
+ superseded: 'answered',
49
+ stale_generation: 'answered',
50
+ missing_identity: 'answered',
51
+ invalid_control_body: 'answered',
52
+ unknown_module: 'answered',
53
+ module_removed: 'answered',
54
+ capability_denied: 'answered',
55
+ unknown_channel: 'unreachable',
56
+ stale_route_epoch: 'unreachable',
57
+ capability_forbidden: 'answered',
58
+ capability_unprovided: 'answered',
59
+ capability_ambiguous: 'answered',
60
+ invalid_capability_identifier: 'answered',
61
+ binary_body_required: 'answered',
62
+ binary_call_requires_call_binary: 'answered',
63
+ corr_exhausted: 'answered',
64
+ late_route_cleanup_failed: 'answered',
65
+ reverse_request_capability_not_declared: 'answered',
66
+ stale_route_handle: 'answered',
67
+ reverse_request_unhandled: 'answered',
68
+ handler_error: 'answered',
69
+ health_error: 'answered',
70
+ duplicate_module_id: 'answered',
71
+ route_rejected: 'answered',
72
+ lock_busy: 'answered',
73
+ owner_invalid: 'answered',
74
+ renewal_failed: 'answered',
75
+ unsupported_platform: 'answered',
76
+ EACCES: 'answered',
77
+ EPERM: 'answered',
78
+ ERR_PRIVATE_FILES_SECURITY: 'answered',
79
+ });
80
+ /**
81
+ * An injected adapter may throw this ONLY when its connection/transport is
82
+ * unreachable, including a failed connect before getScoped. Do not wrap an
83
+ * adapter shutdown, cancellation, validation error or vault refusal in it.
84
+ * Its fixed message cannot echo enrollment or credential material, and its
85
+ * kind stays `unavailable` for callers handling ClaustrumConsumerError.
86
+ */
87
+ export class ClaustrumUnreachableError extends ClaustrumConsumerError {
88
+ constructor() {
89
+ super('unavailable', 'Claustrum scoped operation unavailable');
90
+ this.name = 'ClaustrumUnreachableError';
91
+ }
92
+ }
93
+ export function classifyVaultFailure(error) {
94
+ if (error instanceof ClaustrumUnreachableError ||
95
+ error instanceof SocketClosedError ||
96
+ error instanceof SocketTimeoutError)
97
+ return 'unreachable';
98
+ const code = error instanceof ClaustrumCredentialError || error instanceof SubcCallError
99
+ ? error.code
100
+ : error instanceof Error && 'code' in error
101
+ ? error.code
102
+ : undefined;
103
+ if (typeof code !== 'string' || !Object.hasOwn(VAULT_FAILURE_CLASSES, code))
104
+ return 'answered';
105
+ return VAULT_FAILURE_CLASSES[code];
106
+ }
@@ -1,7 +1,7 @@
1
1
  import type { ClaustrumReporterSource } from '@cortexkit/claustrum-client';
2
2
  import type { QuotaObservation } from '../quota/index.js';
3
3
  import type { RoutingRow } from '../routing/index.js';
4
- import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser, type VaultGrantReach } from './custody.js';
4
+ import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser, type KeptReceiptState, type VaultGrantReach } from './custody.js';
5
5
  import { type ClaustrumLogger } from './errors.js';
6
6
  import { type InsulaQuotaOptions } from './insula.js';
7
7
  import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
@@ -81,6 +81,8 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
81
81
  * held the discovery lease and its newer roster was served instead).
82
82
  */
83
83
  grantReach(): VaultGrantReach | undefined;
84
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
85
+ keptReceiptState(): KeptReceiptState;
84
86
  /** Rows for `/routing`, from the last committed roster. */
85
87
  routingRows(): RoutingRow[];
86
88
  refresh(): Promise<VaultRosterFile | undefined>;
@@ -122,6 +122,11 @@ export class ClaustrumConsumer {
122
122
  ? latest.reach
123
123
  : undefined;
124
124
  }
125
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
126
+ keptReceiptState() {
127
+ return (this.#custody?.keptReceiptState() ??
128
+ Object.freeze({ active: false, since: null }));
129
+ }
125
130
  /** Rows for `/routing`, from the last committed roster. */
126
131
  routingRows() {
127
132
  return vaultRoutingRows(this.#roster);
@@ -164,6 +169,7 @@ export class ClaustrumConsumer {
164
169
  this.#assertOpen();
165
170
  const changed = roster?.view !== this.#roster?.view;
166
171
  this.#roster = roster;
172
+ custody.retain(roster?.rows ?? []);
167
173
  // Each discovery replaces the previous value, including with unknown. A
168
174
  // refresh that served a peer's roster discovered nothing and leaves it;
169
175
  // grantReach() hides it once the roster's view no longer matches.
@@ -282,20 +288,32 @@ export class ClaustrumConsumer {
282
288
  async authorize(routeId, signal) {
283
289
  this.#assertOpen(signal);
284
290
  const roster = this.#roster ?? (await this.#wait(this.refresh(), signal));
285
- if (!roster || !(await this.#active()))
291
+ if (!roster || !(await this.#active())) {
292
+ this.#custody?.close();
293
+ this.#custody = undefined;
294
+ this.#insula?.release();
295
+ this.#insula = undefined;
286
296
  throw new ClaustrumConsumerError('not-active', 'Claustrum scoped custody is not active');
297
+ }
287
298
  const current = await readVaultRoster(this.#options.rosterPath);
288
299
  this.#assertOpen(signal);
289
300
  const observed = roster.rows.find((row) => row.routeId === routeId);
290
301
  const configured = current?.rows.find((row) => row.routeId === routeId);
291
- if (configured && !configured.enabled)
302
+ if (configured && !configured.enabled) {
303
+ if (observed)
304
+ this.#custody?.forget(observed.credentialId);
292
305
  throw new ClaustrumConsumerError('route-declined', 'Claustrum route is disabled');
306
+ }
293
307
  if (!observed ||
294
308
  !configured ||
295
309
  configured.state !== 'active' ||
296
310
  configured.credentialId !== observed.credentialId ||
297
- configured.accountIdentity !== observed.accountIdentity)
311
+ configured.accountIdentity !== observed.accountIdentity ||
312
+ configured.credentialType !== observed.credentialType) {
313
+ if (observed)
314
+ this.#custody?.forget(observed.credentialId);
298
315
  throw new ClaustrumConsumerError('route-unavailable', 'Claustrum route is disabled, removed or changed');
316
+ }
299
317
  const custody = await this.#wait(this.#getCustody(), signal);
300
318
  const combined = combineAbortSignals([
301
319
  this.#shutdown.signal,
@@ -308,7 +326,7 @@ export class ClaustrumConsumer {
308
326
  ...(configured.accountIdentity !== undefined && {
309
327
  accountIdentity: configured.accountIdentity,
310
328
  }),
311
- }, combined.signal);
329
+ }, combined.signal, routeId);
312
330
  }
313
331
  finally {
314
332
  combined.dispose();
@@ -332,6 +350,10 @@ export class ClaustrumConsumer {
332
350
  const signal = options.signal;
333
351
  let served = await this.authorize(routeId, signal);
334
352
  let response = await dispatch(served, signal);
353
+ if (response.status === 401 && served.fromKeptReceipt) {
354
+ await this.reportFailure(served, 401, options.reporterSource ?? 'direct');
355
+ return response;
356
+ }
335
357
  if (response.status === 401 && !signal?.aborted) {
336
358
  let current;
337
359
  try {
@@ -366,6 +388,7 @@ export class ClaustrumConsumer {
366
388
  this.#assertOpen();
367
389
  await declineVaultRoute(this.#options.rosterPath, routeId);
368
390
  this.#roster = await readVaultRoster(this.#options.rosterPath);
391
+ this.#custody?.retain(this.#roster?.rows ?? []);
369
392
  }
370
393
  async accept(routeId) {
371
394
  this.#assertOpen();
@@ -132,6 +132,17 @@ export interface ClaustrumScopedAttempt {
132
132
  readonly accessToken: string;
133
133
  readonly recordVersion: number;
134
134
  readonly expiresAtMs: number | null;
135
+ /**
136
+ * True when this receipt was not freshly served but is the last token kept
137
+ * from an earlier read, used because the vault could not be reached. A 401
138
+ * with such a receipt must not be retried and is not reported to the vault,
139
+ * which is unreachable.
140
+ */
141
+ readonly fromKeptReceipt?: true;
142
+ }
143
+ export interface KeptReceiptState {
144
+ readonly active: boolean;
145
+ readonly since: number | null;
135
146
  }
136
147
  /** Reads the provider identity a served token executes under, when the plugin can tell. */
137
148
  export type IdentityParser = (accessToken: string) => string | undefined;
@@ -151,13 +162,15 @@ export declare function decideScopedRetryAfter401(site: string, served: Claustru
151
162
  * so it cannot expire while a long request is still using it.
152
163
  */
153
164
  export declare const SERVING_MARGIN_MS = 300000;
165
+ /** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
166
+ export declare const KEPT_RECEIPT_MARGIN_MS = 60000;
154
167
  /**
155
168
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
156
- * enrollment token as authorization. Used by every host of a plugin. There is
157
- * deliberately no credential cache and no single-flight of credential reads:
158
- * each physical send is authorized by the vault, so a revoked enrollment or a
159
- * changed record takes effect on the next send. The enrollment token is
160
- * re-read per operation so an operator's reissue on disk is picked up.
169
+ * enrollment token as authorization. Used by every host of a plugin. Every
170
+ * physical send still asks the vault first. Only an unreachable vault permits
171
+ * reuse of the last validated receipt, in memory and bounded by its expiry.
172
+ * The enrollment token is re-read per operation so revocation and disconnect
173
+ * still take effect without a process restart.
161
174
  */
162
175
  export declare class ClaustrumScopedCustody {
163
176
  #private;
@@ -185,16 +198,17 @@ export declare class ClaustrumScopedCustody {
185
198
  * skipped records: they simply are not this consumer's.
186
199
  */
187
200
  discover(signal?: AbortSignal): Promise<VaultInventory>;
188
- /**
189
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
190
- * The vault's served identity (or, without one, the plugin's parse of the
191
- * token) must equal the roster's when both are present. Without
192
- * `requireAssertion`, absence on either side proves nothing and does not
193
- * refuse; the receipt records what the vault asserted separately from what
194
- * the roster expected. With it, a reply that does not itself name the
195
- * credential id and the expected account is refused.
196
- */
197
- authorize(identity: ClaustrumScopedIdentity, signal?: AbortSignal): Promise<ClaustrumScopedAttempt>;
201
+ /** Discard bearer material when a route is removed, declined or rebound. */
202
+ forget(credentialId: string): void;
203
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
204
+ retain(identities: readonly (ClaustrumScopedIdentity & {
205
+ enabled: boolean;
206
+ state: string;
207
+ })[]): void;
208
+ /** A frozen, non-secret summary for a plugin's status display. */
209
+ keptReceiptState(): KeptReceiptState;
210
+ /** Ask the vault first; retain one validated receipt per credential in memory only. */
211
+ authorize(identity: ClaustrumScopedIdentity, signal?: AbortSignal, routeId?: string): Promise<ClaustrumScopedAttempt>;
198
212
  /**
199
213
  * Report that a send this consumer actually made was rejected. Only a 401
200
214
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
@@ -1,11 +1,14 @@
1
1
  import { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
2
2
  import { createLogger } from '../logger/index.js';
3
+ import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability.js';
3
4
  import { readClaustrumEnrollmentToken } from './enrollment.js';
4
5
  import { ClaustrumConsumerError } from './errors.js';
5
6
  import { CUSTODY_PLACEHOLDER_PREFIX } from './host-slot.js';
6
7
  /** Only a new version of the same account may replace an in-flight 401. */
7
8
  export function isScopedCredentialRotation(served, current) {
8
9
  return (current !== undefined &&
10
+ !current.fromKeptReceipt &&
11
+ !served.fromKeptReceipt &&
9
12
  current.credentialId === served.credentialId &&
10
13
  current.accountIdentity === served.accountIdentity &&
11
14
  current.recordVersion !== served.recordVersion);
@@ -45,6 +48,8 @@ export function decideScopedRetryAfter401(site, served, current, logger = defaul
45
48
  * so it cannot expire while a long request is still using it.
46
49
  */
47
50
  export const SERVING_MARGIN_MS = 300_000;
51
+ /** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
52
+ export const KEPT_RECEIPT_MARGIN_MS = 60_000;
48
53
  function invalidMaterial() {
49
54
  return new ClaustrumConsumerError('invalid-material', 'Claustrum returned invalid credential material');
50
55
  }
@@ -100,11 +105,11 @@ function grantReachOf(listed) {
100
105
  }
101
106
  /**
102
107
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
103
- * enrollment token as authorization. Used by every host of a plugin. There is
104
- * deliberately no credential cache and no single-flight of credential reads:
105
- * each physical send is authorized by the vault, so a revoked enrollment or a
106
- * changed record takes effect on the next send. The enrollment token is
107
- * re-read per operation so an operator's reissue on disk is picked up.
108
+ * enrollment token as authorization. Used by every host of a plugin. Every
109
+ * physical send still asks the vault first. Only an unreachable vault permits
110
+ * reuse of the last validated receipt, in memory and bounded by its expiry.
111
+ * The enrollment token is re-read per operation so revocation and disconnect
112
+ * still take effect without a process restart.
108
113
  */
109
114
  export class ClaustrumScopedCustody {
110
115
  #client;
@@ -116,6 +121,8 @@ export class ClaustrumScopedCustody {
116
121
  #logger;
117
122
  #provenance = new WeakMap();
118
123
  #reports = new WeakMap();
124
+ #kept = new Map();
125
+ #keptAttempts = new WeakMap();
119
126
  #closed = false;
120
127
  constructor(options) {
121
128
  const tokenPath = options.tokenPath;
@@ -177,6 +184,8 @@ export class ClaustrumScopedCustody {
177
184
  // request params that include the enrollment token.
178
185
  if (error instanceof ClaustrumCredentialError)
179
186
  throw error;
187
+ if (classifyVaultFailure(error) === 'unreachable')
188
+ throw new ClaustrumUnreachableError();
180
189
  throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation unavailable');
181
190
  }
182
191
  finally {
@@ -192,8 +201,23 @@ export class ClaustrumScopedCustody {
192
201
  * skipped records: they simply are not this consumer's.
193
202
  */
194
203
  async discover(signal) {
195
- const token = await this.#token(signal);
196
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
204
+ let inventory;
205
+ let token;
206
+ try {
207
+ token = await this.#token(signal);
208
+ }
209
+ catch (error) {
210
+ this.#kept.clear();
211
+ throw error;
212
+ }
213
+ try {
214
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
215
+ }
216
+ catch (error) {
217
+ if (classifyVaultFailure(error) !== 'unreachable')
218
+ this.#kept.clear();
219
+ throw error;
220
+ }
197
221
  const skipped = [];
198
222
  const candidates = [];
199
223
  const counts = new Map();
@@ -240,23 +264,106 @@ export class ClaustrumScopedCustody {
240
264
  ...(grantReach && { grantReach }),
241
265
  };
242
266
  }
267
+ /** Discard bearer material when a route is removed, declined or rebound. */
268
+ forget(credentialId) {
269
+ this.#kept.delete(credentialId);
270
+ }
271
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
272
+ retain(identities) {
273
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
274
+ for (const [id, kept] of this.#kept) {
275
+ const identity = current.get(id);
276
+ if (!identity?.enabled ||
277
+ identity.state !== 'active' ||
278
+ identity.credentialType !== kept.attempt.credentialType ||
279
+ identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
280
+ this.forget(id);
281
+ }
282
+ }
283
+ /** A frozen, non-secret summary for a plugin's status display. */
284
+ keptReceiptState() {
285
+ let since = null;
286
+ for (const [id, kept] of this.#kept) {
287
+ if (!this.#usable(kept.attempt)) {
288
+ this.forget(id);
289
+ continue;
290
+ }
291
+ if (kept.since !== null)
292
+ since = Math.min(since ?? kept.since, kept.since);
293
+ }
294
+ return Object.freeze({ active: since !== null, since });
295
+ }
296
+ #usable(attempt) {
297
+ return attempt.expiresAtMs === null
298
+ ? attempt.credentialType === 'api_key'
299
+ : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
300
+ }
301
+ /** Ask the vault first; retain one validated receipt per credential in memory only. */
302
+ async authorize(identity, signal, routeId = 'vault') {
303
+ this.#check(signal);
304
+ const { credentialId, credentialType, accountIdentity } = identity;
305
+ let kept = this.#kept.get(credentialId);
306
+ if (kept &&
307
+ (kept.attempt.credentialType !== credentialType ||
308
+ kept.attempt.expectedAccountIdentity !== accountIdentity)) {
309
+ this.forget(credentialId);
310
+ kept = undefined;
311
+ }
312
+ // A missing or invalid enrollment is not a transport outage.
313
+ let token;
314
+ try {
315
+ token = await this.#token(signal);
316
+ }
317
+ catch (error) {
318
+ this.#kept.clear();
319
+ throw error;
320
+ }
321
+ try {
322
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
323
+ if (kept?.since !== null && kept?.since !== undefined)
324
+ (this.#logger.info ?? defaultLogger.info)('vault receipt serving resumed', { routeId, reason: 'reachable' });
325
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
326
+ return attempt;
327
+ }
328
+ catch (error) {
329
+ this.#check(signal);
330
+ if (classifyVaultFailure(error) !== 'unreachable') {
331
+ this.forget(credentialId);
332
+ throw error;
333
+ }
334
+ // A concurrent refusal or 401 may already have discarded this entry.
335
+ if (!kept ||
336
+ this.#kept.get(credentialId) !== kept ||
337
+ !this.#usable(kept.attempt)) {
338
+ this.forget(credentialId);
339
+ throw error;
340
+ }
341
+ if (kept.since === null) {
342
+ kept.since = this.#now();
343
+ this.#logger.warn('serving kept vault receipt', {
344
+ routeId,
345
+ reason: 'unreachable',
346
+ });
347
+ }
348
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
349
+ this.#provenance.set(attempt, token);
350
+ this.#keptAttempts.set(attempt, routeId);
351
+ return attempt;
352
+ }
353
+ }
243
354
  /**
244
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
245
- * The vault's served identity (or, without one, the plugin's parse of the
246
- * token) must equal the roster's when both are present. Without
247
- * `requireAssertion`, absence on either side proves nothing and does not
248
- * refuse; the receipt records what the vault asserted separately from what
249
- * the roster expected. With it, a reply that does not itself name the
250
- * credential id and the expected account is refused.
355
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
356
+ * (or the plugin's token parse) must agree with the roster when both exist.
357
+ * With requireAssertion, an absent assertion also refuses rather than
358
+ * treating the roster's expectation as proof of the served account.
251
359
  */
252
- async authorize(identity, signal) {
360
+ async #authorizeFresh(identity, token, signal) {
253
361
  if (!identity.credentialId)
254
362
  throw new ClaustrumConsumerError('route-unavailable', 'Claustrum dispatch requires a credential id');
255
363
  // Capture the caller's fields before yielding so a later mutation cannot move the fence.
256
364
  const { credentialId, credentialType, accountIdentity } = identity;
257
365
  if (this.#requireAssertion && accountIdentity === undefined)
258
366
  throw new ClaustrumConsumerError('identity-unasserted', 'Claustrum dispatch requires a known account identity');
259
- const token = await this.#token(signal);
260
367
  const served = await this.#call(() => this.#client.getScoped({
261
368
  credentialId,
262
369
  enrollmentToken: token,
@@ -338,6 +445,21 @@ export class ClaustrumScopedCustody {
338
445
  const token = this.#provenance.get(attempt);
339
446
  if (!token)
340
447
  throw new ClaustrumConsumerError('no-receipt', 'Claustrum failure report requires an original dispatch receipt');
448
+ const keptRoute = this.#keptAttempts.get(attempt);
449
+ if (keptRoute !== undefined) {
450
+ this.forget(attempt.credentialId);
451
+ this.#logger.debug('scoped 401 not reported', {
452
+ routeId: keptRoute,
453
+ reason: 'kept-receipt',
454
+ });
455
+ return;
456
+ }
457
+ // The provider rejected this token, so it must not come back as a kept
458
+ // receipt during a later outage. Drop it before reporting, so a report that
459
+ // fails because the vault is unreachable still drops it.
460
+ const kept = this.#kept.get(attempt.credentialId);
461
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
462
+ this.forget(attempt.credentialId);
341
463
  const pending = this.#reports.get(attempt);
342
464
  if (pending)
343
465
  return pending;
@@ -366,6 +488,7 @@ export class ClaustrumScopedCustody {
366
488
  if (this.#closed)
367
489
  return;
368
490
  this.#closed = true;
491
+ this.#kept.clear();
369
492
  this.#client.close();
370
493
  }
371
494
  }
@@ -11,6 +11,7 @@ export declare class ClaustrumConsumerError extends Error {
11
11
  }
12
12
  /** The structural logger every class here accepts; `/logger`'s `createLogger` satisfies it. */
13
13
  export interface ClaustrumLogger {
14
+ info?(message: string, data?: unknown): void;
14
15
  warn(message: string, data?: unknown): void;
15
16
  debug(message: string, data?: unknown): void;
16
17
  }
@@ -1,12 +1,13 @@
1
1
  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
+ export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
4
5
  export { ClaustrumConsumer, type ClaustrumConsumerOptions, type SendOptions, } from './consumer.js';
5
- export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, } from './custody.js';
6
+ export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, } from './custody.js';
6
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';
7
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
8
9
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
9
- export type { InsulaQuotaContext, InsulaQuotaOptions, InsulaUsageEntry, InsulaUsageTransport, InsulaUsageWindow, } from './insula.js';
10
+ export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaOptions, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWindow, } from './insula.js';
10
11
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
11
12
  export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
12
13
  /**
@@ -6,11 +6,13 @@
6
6
  import { ClaustrumClient, } from '@cortexkit/claustrum-client';
7
7
  import { insulaUsageTransport } from './insula.js';
8
8
  export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
9
+ export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from './availability.js';
9
10
  export { ClaustrumConsumer, } from './consumer.js';
10
- export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, SERVING_MARGIN_MS, } from './custody.js';
11
+ export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from './custody.js';
11
12
  export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
12
13
  export { ClaustrumConsumerError, } from './errors.js';
13
14
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
15
+ export { acquireInsulaQuotaSource, } from './insula.js';
14
16
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
15
17
  export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
16
18
  /**
@@ -184,19 +184,25 @@ export async function replaceWindowsFile(from, to, options = {}) {
184
184
  to = resolve(to);
185
185
  const now = options.now ?? (() => performance.now());
186
186
  const start = now();
187
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
187
+ const leaseDeadline = options.deadline ?? Infinity;
188
+ let retryDeadline;
188
189
  const delays = [0, 10, 20, 40, 80, 100];
189
190
  let original;
190
191
  let attempts = 0;
191
192
  for (const delay of delays) {
193
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
192
194
  if (now() >= deadline)
193
195
  break;
194
196
  if (delay)
195
197
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay, Math.max(0, deadline - now())));
196
198
  if (now() >= deadline)
197
199
  break;
200
+ const fenceStart = now();
198
201
  await options.beforeRename?.();
199
- if (now() >= deadline)
202
+ // Ownership checks fence every attempt but do not spend the sharing-retry budget.
203
+ if (retryDeadline !== undefined)
204
+ retryDeadline += now() - fenceStart;
205
+ if (now() >= leaseDeadline)
200
206
  break;
201
207
  attempts++;
202
208
  try {
@@ -212,6 +218,8 @@ export async function replaceWindowsFile(from, to, options = {}) {
212
218
  !detail.reason;
213
219
  if (!candidate)
214
220
  break;
221
+ // Start the retry window only once a rename has actually failed.
222
+ retryDeadline ??= now() + 500;
215
223
  }
216
224
  }
217
225
  const error = new PrivateFileError(to, 'rename', original ??
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -111,12 +111,12 @@
111
111
  "jsonc-parser": "^3.3.1"
112
112
  },
113
113
  "peerDependencies": {
114
- "@opentui/core": ">=0.5.11",
115
- "@opentui/solid": ">=0.5.11",
116
- "solid-js": "1.9.12",
117
114
  "@cortexkit/claustrum-client": ">=0.6.2",
118
115
  "@cortexkit/subc-client": "^0.16.0",
119
- "@opencode/plugin": ">=2.0.21"
116
+ "@opencode/plugin": ">=2.0.21",
117
+ "@opentui/core": ">=0.5.11",
118
+ "@opentui/solid": ">=0.5.11",
119
+ "solid-js": "1.9.12"
120
120
  },
121
121
  "peerDependenciesMeta": {
122
122
  "@opentui/core": {