@cortexkit/common-auth 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@ import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScoped
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';
8
+ import { type WatchMode } from './watch.js';
8
9
  export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
9
10
  /**
10
11
  * The roster file: one row per vault account (route id, credential id,
@@ -41,6 +42,12 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
41
42
  */
42
43
  onRoster?: (roster: VaultRosterFile) => void;
43
44
  onError?: (error: unknown) => void;
45
+ /**
46
+ * How often `start()` ticks. A tick lists the vault when no vault watch is
47
+ * open (before it is accepted, or when the vault or the client cannot
48
+ * watch), and otherwise only every five minutes, as a safety net. A tick
49
+ * polls insula (at most once a minute) only while its watch is not open.
50
+ */
44
51
  pollIntervalMs?: number;
45
52
  setTimeoutImpl?: typeof setTimeout;
46
53
  clearTimeoutImpl?: typeof clearTimeout;
@@ -49,6 +56,15 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
49
56
  /** Optional background quota source. In-band readings still use recordQuota. */
50
57
  insula?: InsulaQuotaOptions<Q>;
51
58
  }
59
+ /**
60
+ * How a started consumer learns about changes, for logs and status displays.
61
+ * `insula` is present when the consumer was given an insula source. Never
62
+ * carries secrets.
63
+ */
64
+ export interface ClaustrumWatchState {
65
+ readonly vault: WatchMode;
66
+ readonly insula?: WatchMode;
67
+ }
52
68
  export interface SendOptions {
53
69
  /**
54
70
  * What kind of request this is (for example `model`, `quota`, `profile`),
@@ -81,11 +97,23 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
81
97
  * held the discovery lease and its newer roster was served instead).
82
98
  */
83
99
  grantReach(): VaultGrantReach | undefined;
100
+ /** How this consumer currently learns about changes, without I/O. */
101
+ watchState(): ClaustrumWatchState;
84
102
  /** Whether any account is using an in-memory outage receipt, without I/O. */
85
103
  keptReceiptState(): KeptReceiptState;
86
104
  /** Rows for `/routing`, from the last committed roster. */
87
105
  routingRows(): RoutingRow[];
88
106
  refresh(): Promise<VaultRosterFile | undefined>;
107
+ /**
108
+ * Poll in the background and open the vault and insula watches. Until the
109
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
110
+ * the vault exactly as before watches existed. While it is open a tick
111
+ * lists only when five minutes have passed since the last discovery, since
112
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
113
+ * to local mode closes the connection as quickly as before. Insula is
114
+ * polled on the tick only while its own watch is not open. A host not in
115
+ * vault mode makes no request.
116
+ */
89
117
  start(): void;
90
118
  /**
91
119
  * Fetch on a background tick, at most once per minute across projects with
@@ -5,6 +5,7 @@ import { readClaustrumEnrollmentToken } from './enrollment.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { acquireInsulaQuotaSource } from './insula.js';
7
7
  import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
8
+ import { SAFETY_POLL_MS } from './watch.js';
8
9
  /**
9
10
  * One plugin host's view of its vault accounts. It turns vault credentials
10
11
  * into rows for `/routing`, authorizes each physical send with the vault, and
@@ -29,6 +30,10 @@ export class ClaustrumConsumer {
29
30
  #timer;
30
31
  #started = false;
31
32
  #insula;
33
+ #vaultWatch;
34
+ #releaseInsulaWatch;
35
+ /** When this instance last completed a discovery, by `now`. */
36
+ #discoveredAt;
32
37
  constructor(options) {
33
38
  this.#options = options;
34
39
  this.#logger = options.logger ?? createLogger('claustrum');
@@ -91,6 +96,8 @@ export class ClaustrumConsumer {
91
96
  requireAssertion: this.#options.requireAssertion,
92
97
  now: this.#options.now,
93
98
  logger: this.#logger,
99
+ setTimeoutImpl: this.#options.setTimeoutImpl,
100
+ clearTimeoutImpl: this.#options.clearTimeoutImpl,
94
101
  });
95
102
  if (this.#options.insula && client.insula) {
96
103
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -122,6 +129,22 @@ export class ClaustrumConsumer {
122
129
  ? latest.reach
123
130
  : undefined;
124
131
  }
132
+ /** How this consumer currently learns about changes, without I/O. */
133
+ watchState() {
134
+ return Object.freeze({
135
+ vault: this.#vaultWatch?.mode ?? 'polling',
136
+ ...(this.#options.insula && {
137
+ insula: this.#insula?.source.watchMode() ?? 'polling',
138
+ }),
139
+ });
140
+ }
141
+ /** Close the watches with the connection they belong to. */
142
+ #stopWatch() {
143
+ this.#vaultWatch?.close();
144
+ this.#vaultWatch = undefined;
145
+ this.#releaseInsulaWatch?.();
146
+ this.#releaseInsulaWatch = undefined;
147
+ }
125
148
  /** Whether any account is using an in-memory outage receipt, without I/O. */
126
149
  keptReceiptState() {
127
150
  return (this.#custody?.keptReceiptState() ??
@@ -139,6 +162,7 @@ export class ClaustrumConsumer {
139
162
  if (!(await this.#active())) {
140
163
  this.#roster = undefined;
141
164
  this.#grantReach = undefined;
165
+ this.#stopWatch();
142
166
  this.#custody?.close();
143
167
  this.#custody = undefined;
144
168
  this.#insula?.release();
@@ -181,12 +205,23 @@ export class ClaustrumConsumer {
181
205
  // notification, and the poll runs every few seconds.
182
206
  if (roster && changed)
183
207
  this.#options.onRoster?.(roster);
208
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
184
209
  return roster;
185
210
  })().finally(() => {
186
211
  this.#refreshing = undefined;
187
212
  });
188
213
  return this.#refreshing;
189
214
  }
215
+ /**
216
+ * Poll in the background and open the vault and insula watches. Until the
217
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
218
+ * the vault exactly as before watches existed. While it is open a tick
219
+ * lists only when five minutes have passed since the last discovery, since
220
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
221
+ * to local mode closes the connection as quickly as before. Insula is
222
+ * polled on the tick only while its own watch is not open. A host not in
223
+ * vault mode makes no request.
224
+ */
190
225
  start() {
191
226
  if (this.#started)
192
227
  return;
@@ -194,8 +229,10 @@ export class ClaustrumConsumer {
194
229
  this.#started = true;
195
230
  const tick = async () => {
196
231
  try {
197
- await this.refresh();
232
+ if (await this.#listDue())
233
+ await this.refresh();
198
234
  await this.refreshInsulaQuota();
235
+ this.#openWatch();
199
236
  }
200
237
  catch (error) {
201
238
  if (!this.#shutdown.signal.aborted)
@@ -214,6 +251,53 @@ export class ClaustrumConsumer {
214
251
  };
215
252
  void tick();
216
253
  }
254
+ /** Whether a background tick must list the vault now. */
255
+ async #listDue() {
256
+ if (this.#vaultWatch?.mode !== 'watching')
257
+ return true;
258
+ const now = (this.#options.now ?? Date.now)();
259
+ if (this.#discoveredAt === undefined ||
260
+ now - this.#discoveredAt >= SAFETY_POLL_MS)
261
+ return true;
262
+ // refresh() is what closes the connection when the host left vault mode.
263
+ return !(await this.#active());
264
+ }
265
+ /**
266
+ * Open the vault and insula watches once a vault connection exists. Only
267
+ * reached in vault mode: a host in local mode never connects.
268
+ */
269
+ #openWatch() {
270
+ const custody = this.#custody;
271
+ if (this.#shutdown.signal.aborted || !custody)
272
+ return;
273
+ // The same entry point a host without a consumer uses, so both apply
274
+ // notices, refusals and outages alike.
275
+ this.#vaultWatch ??= custody.watchRoster({
276
+ view: () => this.#roster?.view,
277
+ // The existing discovery, so a watched change commits the roster and
278
+ // re-applies it to kept receipts exactly as a poll does. A refresh
279
+ // already in flight may have listed before the change was announced,
280
+ // so wait for it and list again.
281
+ onView: async () => {
282
+ while (this.#refreshing)
283
+ await this.#refreshing.catch(() => { });
284
+ await this.refresh();
285
+ },
286
+ // Custody has dropped kept receipts, as a poll meeting the same
287
+ // refusal from list_scoped would.
288
+ onRefused: (error) => this.#options.onError?.(error),
289
+ onError: (error) => {
290
+ if (!this.#shutdown.signal.aborted)
291
+ this.#options.onError?.(error);
292
+ },
293
+ });
294
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
295
+ this.#releaseInsulaWatch = this.#insula.source.watch({
296
+ provider: this.#options.insula.provider,
297
+ setTimeoutImpl: this.#options.setTimeoutImpl,
298
+ clearTimeoutImpl: this.#options.clearTimeoutImpl,
299
+ });
300
+ }
217
301
  /**
218
302
  * Fetch on a background tick, at most once per minute across projects with
219
303
  * the same daemon and enrollment token path. Admission must use the cache
@@ -291,6 +375,7 @@ export class ClaustrumConsumer {
291
375
  if (!roster || !(await this.#active())) {
292
376
  this.#custody?.close();
293
377
  this.#custody = undefined;
378
+ this.#stopWatch();
294
379
  this.#insula?.release();
295
380
  this.#insula = undefined;
296
381
  throw new ClaustrumConsumerError('not-active', 'Claustrum scoped custody is not active');
@@ -444,6 +529,7 @@ export class ClaustrumConsumer {
444
529
  if (this.#timer)
445
530
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
446
531
  this.#timer = undefined;
532
+ this.#stopWatch();
447
533
  this.#custody?.close();
448
534
  this.#insula?.release();
449
535
  this.#insula = undefined;
@@ -1,9 +1,14 @@
1
1
  import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile } from '@cortexkit/claustrum-client';
2
2
  import { type ClaustrumLogger } from './errors.js';
3
3
  import type { InsulaUsageTransport } from './insula.js';
4
+ import { type ScopedWatchSource, type WatchMode } from './watch.js';
5
+ /**
6
+ * `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
7
+ * run time and keep polling without it.
8
+ */
4
9
  export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
5
10
  insula?: InsulaUsageTransport;
6
- };
11
+ } & ScopedWatchSource;
7
12
  /** The two credential types a plugin's family can hold; routing differs by type. */
8
13
  export type VaultCredentialType = 'oauth' | 'api_key';
9
14
  /**
@@ -144,6 +149,46 @@ export interface KeptReceiptState {
144
149
  readonly active: boolean;
145
150
  readonly since: number | null;
146
151
  }
152
+ export interface ClaustrumRosterWatchOptions {
153
+ /**
154
+ * Run the host's own discovery (`custody.discover()`, then its roster
155
+ * commit). Called with the newest notice's view when that view differs from
156
+ * the last discovered one, when a notice shows a sequence gap or a new
157
+ * epoch, and on the first notice of a watch re-opened after a close (the
158
+ * time between two watches was not observed). One call runs at a time;
159
+ * notices that arrive meanwhile earn at most one more call, which runs only
160
+ * if the view still differs. A rejection goes to `onError`.
161
+ */
162
+ onView: (view: string) => unknown;
163
+ /**
164
+ * The view of the roster the host last committed. Defaults to the view of
165
+ * the last successful `custody.discover()` (outage probes excluded). Pass it
166
+ * when the host can commit a roster it did not list itself (a peer process
167
+ * held the discovery lease) or can fail after listing.
168
+ */
169
+ view?: () => string | undefined;
170
+ /**
171
+ * Called whenever the mode changes. The watch starts in `polling`. Keep the
172
+ * host's own list timer at its usual pace unless the mode is `watching`.
173
+ */
174
+ onMode?: (mode: WatchMode) => void;
175
+ /**
176
+ * The vault refused the watch, and its confirming `list_scoped` read it with
177
+ * this error (a revoked enrollment answers `not_found`). Custody has already
178
+ * applied it as it applies a refused discovery (`listFailed`: every kept
179
+ * receipt is dropped); handle it as the host handles that refusal.
180
+ */
181
+ onRefused?: (error: unknown) => void;
182
+ /** A failed `onView`, or a watch that could not be opened. */
183
+ onError?: (error: unknown) => void;
184
+ }
185
+ /** A vault watch held by a custody; see `ClaustrumScopedCustody.watchRoster`. */
186
+ export interface ClaustrumRosterWatch {
187
+ /** How the host currently learns about changes. */
188
+ readonly mode: WatchMode;
189
+ /** Stop the watch and its timers. Safe to call more than once. */
190
+ close(): void;
191
+ }
147
192
  /** Reads the provider identity a served token executes under, when the plugin can tell. */
148
193
  export type IdentityParser = (accessToken: string) => string | undefined;
149
194
  /** Only a new version of the same account may replace an in-flight 401. */
@@ -167,7 +212,7 @@ export declare const KEPT_RECEIPT_MARGIN_MS = 60000;
167
212
  /**
168
213
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
169
214
  * 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
215
+ * physical send asks the vault first while reachable. Only an unreachable vault permits
171
216
  * reuse of the last validated receipt, in memory and bounded by its expiry.
172
217
  * The enrollment token is re-read per operation so revocation and disconnect
173
218
  * still take effect without a process restart.
@@ -190,7 +235,13 @@ export declare class ClaustrumScopedCustody {
190
235
  requireAssertion?: boolean;
191
236
  now?: () => number;
192
237
  logger?: ClaustrumLogger;
238
+ setTimeoutImpl?: typeof setTimeout;
239
+ clearTimeoutImpl?: typeof clearTimeout;
193
240
  });
241
+ /** A watch losing its transport is the same outage as an unreachable read. */
242
+ transportLost(error?: unknown): void;
243
+ /** Any vault answer ends transport fallback, even when it refuses access. */
244
+ reachable(): void;
194
245
  /**
195
246
  * List this consumer's credentials. A record that cannot be used is skipped
196
247
  * and warned about rather than failing the whole list, so one bad record
@@ -198,6 +249,13 @@ export declare class ClaustrumScopedCustody {
198
249
  * skipped records: they simply are not this consumer's.
199
250
  */
200
251
  discover(signal?: AbortSignal): Promise<VaultInventory>;
252
+ /**
253
+ * Apply a failed account listing: any answer from the vault (a refusal such
254
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
255
+ * unreachable vault keeps them. A vault watch that ends with the same
256
+ * refusal calls this too, so both paths treat it alike.
257
+ */
258
+ listFailed(error: unknown): void;
201
259
  /** Discard bearer material when a route is removed, declined or rebound. */
202
260
  forget(credentialId: string): void;
203
261
  /** Apply an already-held roster; this never fetches credentials or writes it. */
@@ -207,7 +265,7 @@ export declare class ClaustrumScopedCustody {
207
265
  })[]): void;
208
266
  /** A frozen, non-secret summary for a plugin's status display. */
209
267
  keptReceiptState(): KeptReceiptState;
210
- /** Ask the vault first; retain one validated receipt per credential in memory only. */
268
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
211
269
  authorize(identity: ClaustrumScopedIdentity, signal?: AbortSignal, routeId?: string): Promise<ClaustrumScopedAttempt>;
212
270
  /**
213
271
  * Report that a send this consumer actually made was rejected. Only a 401
@@ -217,5 +275,25 @@ export declare class ClaustrumScopedCustody {
217
275
  * custody did not issue is refused rather than reported.
218
276
  */
219
277
  reportFailure(attempt: ClaustrumScopedAttempt, status: number, reporterSource: ClaustrumReporterSource): Promise<void>;
278
+ /**
279
+ * Watch this consumer's visible vault accounts instead of listing them on a
280
+ * short timer. Opens one `watchScoped` on this custody's client and calls
281
+ * `onView` when the host must run its discovery (see
282
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
283
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
284
+ * `fallback` and opens nothing. A watch that closes before any notice was
285
+ * never accepted: the client reads once to learn why, and the watch reports
286
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
287
+ * loop. A watch that closes after notices is re-opened after
288
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
289
+ * starts this custody's outage, exactly as an unreachable call does, and
290
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
291
+ * on the returned watch or on this custody stops it.
292
+ *
293
+ * The watch keeps no history, so the host still lists on a slow timer while
294
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
295
+ * other mode the host keeps its usual list timer.
296
+ */
297
+ watchRoster(options: ClaustrumRosterWatchOptions): ClaustrumRosterWatch;
220
298
  close(): void;
221
299
  }
@@ -4,6 +4,7 @@ import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability
4
4
  import { readClaustrumEnrollmentToken } from './enrollment.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { CUSTODY_PLACEHOLDER_PREFIX } from './host-slot.js';
7
+ import { ScopedRosterWatch, } from './watch.js';
7
8
  /** Only a new version of the same account may replace an in-flight 401. */
8
9
  export function isScopedCredentialRotation(served, current) {
9
10
  return (current !== undefined &&
@@ -106,7 +107,7 @@ function grantReachOf(listed) {
106
107
  /**
107
108
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
108
109
  * 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
+ * physical send asks the vault first while reachable. Only an unreachable vault permits
110
111
  * reuse of the last validated receipt, in memory and bounded by its expiry.
111
112
  * The enrollment token is re-read per operation so revocation and disconnect
112
113
  * still take effect without a process restart.
@@ -123,7 +124,18 @@ export class ClaustrumScopedCustody {
123
124
  #reports = new WeakMap();
124
125
  #kept = new Map();
125
126
  #keptAttempts = new WeakMap();
127
+ #setTimeout;
128
+ #clearTimeout;
129
+ #outage = false;
130
+ #outageError = new ClaustrumUnreachableError();
131
+ #probeTimer;
132
+ #probing = false;
133
+ #lastProbeAt = -Infinity;
134
+ #probeDelay = 2_000;
126
135
  #closed = false;
136
+ /** The view of the last successful `discover()`, for `watchRoster`. */
137
+ #discoveredView;
138
+ #watches = new Set();
127
139
  constructor(options) {
128
140
  const tokenPath = options.tokenPath;
129
141
  if (options.readToken) {
@@ -141,6 +153,65 @@ export class ClaustrumScopedCustody {
141
153
  this.#requireAssertion = options.requireAssertion ?? false;
142
154
  this.#now = options.now ?? Date.now;
143
155
  this.#logger = options.logger ?? defaultLogger;
156
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
157
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
158
+ }
159
+ /** A watch losing its transport is the same outage as an unreachable read. */
160
+ transportLost(error) {
161
+ if (this.#closed || this.#outage)
162
+ return;
163
+ this.#outage = true;
164
+ this.#outageError =
165
+ error instanceof ClaustrumCredentialError
166
+ ? error
167
+ : new ClaustrumUnreachableError();
168
+ this.#logger.warn('serving kept vault receipt', { reason: 'unreachable' });
169
+ this.#scheduleProbe();
170
+ }
171
+ /** Any vault answer ends transport fallback, even when it refuses access. */
172
+ reachable() {
173
+ if (this.#closed || !this.#outage)
174
+ return;
175
+ this.#outage = false;
176
+ if (this.#probeTimer)
177
+ this.#clearTimeout(this.#probeTimer);
178
+ this.#probeTimer = undefined;
179
+ this.#probeDelay = 2_000;
180
+ for (const kept of this.#kept.values())
181
+ kept.since = null;
182
+ (this.#logger.info ?? defaultLogger.info)('vault receipt serving resumed', { reason: 'reachable' });
183
+ }
184
+ #scheduleProbe() {
185
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
186
+ return;
187
+ this.#probeTimer = this.#setTimeout(() => {
188
+ this.#probeTimer = undefined;
189
+ this.#probe(true);
190
+ }, this.#probeDelay);
191
+ this.#probeTimer.unref?.();
192
+ }
193
+ #probe(idle = false) {
194
+ if (this.#closed || !this.#outage || this.#probing)
195
+ return;
196
+ if (this.#now() - this.#lastProbeAt < 1_000) {
197
+ this.#scheduleProbe();
198
+ return;
199
+ }
200
+ this.#lastProbeAt = this.#now();
201
+ this.#probing = true;
202
+ // Both triggers share list_scoped discovery, including its receipt-drop rules.
203
+ // Sends never await discovery or let idle backoff delay the next send probe.
204
+ // A probe commits no roster, so it is not the host's discovery and does
205
+ // not move the view a roster watch compares notices against.
206
+ void this.#list()
207
+ .catch(() => {
208
+ if (idle && this.#outage)
209
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 30_000);
210
+ })
211
+ .finally(() => {
212
+ this.#probing = false;
213
+ this.#scheduleProbe();
214
+ });
144
215
  }
145
216
  #check(signal) {
146
217
  if (this.#closed)
@@ -179,6 +250,10 @@ export class ClaustrumScopedCustody {
179
250
  }
180
251
  catch (error) {
181
252
  this.#check(signal);
253
+ if (classifyVaultFailure(error) === 'unreachable')
254
+ this.transportLost(error);
255
+ else
256
+ this.reachable();
182
257
  // Keep the vault's own refusals (ClaustrumCredentialError, carrying
183
258
  // code, class and action); replace any other error, whose text may echo
184
259
  // request params that include the enrollment token.
@@ -192,6 +267,7 @@ export class ClaustrumScopedCustody {
192
267
  removeAbortListener?.();
193
268
  }
194
269
  this.#check(signal);
270
+ this.reachable();
195
271
  return result;
196
272
  }
197
273
  /**
@@ -201,6 +277,11 @@ export class ClaustrumScopedCustody {
201
277
  * skipped records: they simply are not this consumer's.
202
278
  */
203
279
  async discover(signal) {
280
+ const inventory = await this.#list(signal);
281
+ this.#discoveredView = inventory.view;
282
+ return inventory;
283
+ }
284
+ async #list(signal) {
204
285
  let inventory;
205
286
  let token;
206
287
  try {
@@ -214,8 +295,7 @@ export class ClaustrumScopedCustody {
214
295
  inventory = await this.#call(() => this.#client.listScoped(token), signal);
215
296
  }
216
297
  catch (error) {
217
- if (classifyVaultFailure(error) !== 'unreachable')
218
- this.#kept.clear();
298
+ this.listFailed(error);
219
299
  throw error;
220
300
  }
221
301
  const skipped = [];
@@ -264,6 +344,20 @@ export class ClaustrumScopedCustody {
264
344
  ...(grantReach && { grantReach }),
265
345
  };
266
346
  }
347
+ /**
348
+ * Apply a failed account listing: any answer from the vault (a refusal such
349
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
350
+ * unreachable vault keeps them. A vault watch that ends with the same
351
+ * refusal calls this too, so both paths treat it alike.
352
+ */
353
+ listFailed(error) {
354
+ if (classifyVaultFailure(error) === 'unreachable')
355
+ this.transportLost(error);
356
+ else {
357
+ this.reachable();
358
+ this.#kept.clear();
359
+ }
360
+ }
267
361
  /** Discard bearer material when a route is removed, declined or rebound. */
268
362
  forget(credentialId) {
269
363
  this.#kept.delete(credentialId);
@@ -298,7 +392,7 @@ export class ClaustrumScopedCustody {
298
392
  ? attempt.credentialType === 'api_key'
299
393
  : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
300
394
  }
301
- /** Ask the vault first; retain one validated receipt per credential in memory only. */
395
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
302
396
  async authorize(identity, signal, routeId = 'vault') {
303
397
  this.#check(signal);
304
398
  const { credentialId, credentialType, accountIdentity } = identity;
@@ -318,10 +412,12 @@ export class ClaustrumScopedCustody {
318
412
  this.#kept.clear();
319
413
  throw error;
320
414
  }
415
+ if (this.#outage && kept) {
416
+ this.#probe();
417
+ return this.#serveKept(credentialId, kept, token, routeId);
418
+ }
321
419
  try {
322
420
  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
421
  this.#kept.set(credentialId, { attempt, routeId, since: null });
326
422
  return attempt;
327
423
  }
@@ -331,25 +427,23 @@ export class ClaustrumScopedCustody {
331
427
  this.forget(credentialId);
332
428
  throw error;
333
429
  }
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;
430
+ return this.#serveKept(credentialId, kept, token, routeId, error);
431
+ }
432
+ }
433
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
434
+ // A concurrent refusal or 401 may already have discarded this entry.
435
+ if (!kept ||
436
+ this.#kept.get(credentialId) !== kept ||
437
+ !this.#usable(kept.attempt)) {
438
+ this.forget(credentialId);
439
+ throw error;
352
440
  }
441
+ if (kept.since === null)
442
+ kept.since = this.#now();
443
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
444
+ this.#provenance.set(attempt, token);
445
+ this.#keptAttempts.set(attempt, routeId);
446
+ return attempt;
353
447
  }
354
448
  /**
355
449
  * Fetch and validate a fresh receipt before retaining it. The vault assertion
@@ -484,10 +578,71 @@ export class ClaustrumScopedCustody {
484
578
  throw error;
485
579
  }
486
580
  }
581
+ /**
582
+ * Watch this consumer's visible vault accounts instead of listing them on a
583
+ * short timer. Opens one `watchScoped` on this custody's client and calls
584
+ * `onView` when the host must run its discovery (see
585
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
586
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
587
+ * `fallback` and opens nothing. A watch that closes before any notice was
588
+ * never accepted: the client reads once to learn why, and the watch reports
589
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
590
+ * loop. A watch that closes after notices is re-opened after
591
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
592
+ * starts this custody's outage, exactly as an unreachable call does, and
593
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
594
+ * on the returned watch or on this custody stops it.
595
+ *
596
+ * The watch keeps no history, so the host still lists on a slow timer while
597
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
598
+ * other mode the host keeps its usual list timer.
599
+ */
600
+ watchRoster(options) {
601
+ this.#check();
602
+ const watch = new ScopedRosterWatch({
603
+ client: this.#client,
604
+ enrollmentToken: () => this.#token(),
605
+ view: options.view ?? (() => this.#discoveredView),
606
+ discover: async (view) => {
607
+ await options.onView(view);
608
+ },
609
+ onRefused: (error) => {
610
+ // Apply a refused watch as discover() applies a refused account
611
+ // listing: every kept receipt is dropped.
612
+ this.listFailed(error);
613
+ options.onRefused?.(error);
614
+ },
615
+ onTransportLost: () => this.transportLost(),
616
+ onReachable: () => this.reachable(),
617
+ onError: options.onError,
618
+ onMode: options.onMode,
619
+ logger: this.#logger,
620
+ now: this.#now,
621
+ setTimeoutImpl: this.#setTimeout,
622
+ clearTimeoutImpl: this.#clearTimeout,
623
+ });
624
+ this.#watches.add(watch);
625
+ watch.start();
626
+ return {
627
+ get mode() {
628
+ return watch.mode;
629
+ },
630
+ close: () => {
631
+ this.#watches.delete(watch);
632
+ watch.stop();
633
+ },
634
+ };
635
+ }
487
636
  close() {
488
637
  if (this.#closed)
489
638
  return;
490
639
  this.#closed = true;
640
+ if (this.#probeTimer)
641
+ this.#clearTimeout(this.#probeTimer);
642
+ this.#probeTimer = undefined;
643
+ for (const watch of this.#watches)
644
+ watch.stop();
645
+ this.#watches.clear();
491
646
  this.#kept.clear();
492
647
  this.#client.close();
493
648
  }
@@ -2,14 +2,15 @@ import { type ClaustrumClientOptions } from '@cortexkit/claustrum-client';
2
2
  import type { ClaustrumScopedClient } from './custody.js';
3
3
  export { ClaustrumCredentialError, type ClaustrumReporterSource, type EnrollmentTokenFile, } from '@cortexkit/claustrum-client';
4
4
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
5
- export { ClaustrumConsumer, type ClaustrumConsumerOptions, type SendOptions, } from './consumer.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';
5
+ export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, type SendOptions, } from './consumer.js';
6
+ export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, } from './custody.js';
7
7
  export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
9
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
10
- export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaOptions, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWindow, } from './insula.js';
10
+ export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaOptions, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } from './insula.js';
11
11
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
12
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';
13
+ export { type ChangeNotice, ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, type ScopedRosterWatchOptions, type ScopedWatchEnd, type ScopedWatchHandle, type ScopedWatchNoticeShape, type ScopedWatchSource, WATCH_RETRY_MS, type WatchMode, } from './watch.js';
13
14
  /**
14
15
  * Connect the client that lists and fetches this consumer's vault credentials
15
16
  * on the request path. `connectionFile` is required: this library