@cortexkit/common-auth 0.39.1 → 0.40.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.
@@ -1,3 +1,4 @@
1
+ import { hasVaultHost, VAULT_HOST_STATUS } from '../claustrum/host.js';
1
2
  import { formatQuota, isQuotaMap, projectQuota, quotaTextParts, } from '../quota/index.js';
2
3
  import { PoolOperationError, } from '../store/index.js';
3
4
  import { doctorAction } from './doctor.js';
@@ -339,7 +340,7 @@ export function deleteAllAction(options) {
339
340
  * quotas, doctor and the extras; nothing that adds, signs in or removes.
340
341
  */
341
342
  export async function accountMenuActions(options) {
342
- return actionsFor(options, (await options.custody?.()) === true);
343
+ return actionsFor(options, hasVaultHost() || (await options.custody?.()) === true);
343
344
  }
344
345
  function actionsFor(options, custody) {
345
346
  const doctor = options.doctor?.length
@@ -369,7 +370,8 @@ function actionsFor(options, custody) {
369
370
  }
370
371
  /** Shows the account menu once and runs the chosen action. */
371
372
  export async function runAccountMenu(options) {
372
- const custody = (await options.custody?.()) === true;
373
+ const hosted = hasVaultHost();
374
+ const custody = hosted || (await options.custody?.()) === true;
373
375
  const actions = actionsFor(options, custody);
374
376
  const [read, status] = await Promise.all([
375
377
  readRows(options.store),
@@ -380,7 +382,11 @@ export async function runAccountMenu(options) {
380
382
  subtitle: custody
381
383
  ? 'Accounts come from the vault; select an action'
382
384
  : 'Select an account action',
383
- status: [...status, ...accountLines(read)],
385
+ status: [
386
+ ...status,
387
+ ...(hosted ? [VAULT_HOST_STATUS] : []),
388
+ ...accountLines(read),
389
+ ],
384
390
  actions,
385
391
  ...(options.terminal ? { terminal: options.terminal } : {}),
386
392
  });
@@ -18,7 +18,10 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
18
18
  /** This host's enrollment token, written by setup. */
19
19
  tokenPath: string;
20
20
  family: ClaustrumFamily;
21
- connect: () => Promise<ClaustrumScopedClient>;
21
+ /** Enrollment-name prefix, required by the default host connection. */
22
+ pluginId?: string;
23
+ /** Used outside host authority; hosted connections always use the relay. */
24
+ connect?: () => Promise<ClaustrumScopedClient>;
22
25
  /**
23
26
  * How long one `connect()` attempt may take before this consumer treats the
24
27
  * vault as unreachable (default 10 s). A connect that never settles would
@@ -31,6 +34,7 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
31
34
  * Whether the plugin currently takes its accounts from the vault (custody
32
35
  * mode) rather than from local logins. Checked before every discovery,
33
36
  * commit and dispatch; false closes the vault connection and refuses sends.
37
+ * Host authority always selects custody and does not call this callback.
34
38
  */
35
39
  isCustodyActive?: () => boolean | Promise<boolean>;
36
40
  /** Ids of the plugin's local pool rows; no vault route id may equal one. */
@@ -4,6 +4,7 @@ import { ClaustrumUnreachableError } from './availability.js';
4
4
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
5
5
  import { readClaustrumEnrollmentToken } from './enrollment.js';
6
6
  import { ClaustrumConsumerError } from './errors.js';
7
+ import { connectVaultHost, hasVaultHost } from './host.js';
7
8
  import { acquireInsulaQuotaSource, } from './insula.js';
8
9
  import { pendingVaultQuota, retainVaultQuotaWriter } from './quota-writer.js';
9
10
  import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, vaultRoutingRows, } from './roster.js';
@@ -98,6 +99,8 @@ export class ClaustrumConsumer {
98
99
  return pending;
99
100
  }
100
101
  async #active() {
102
+ if (hasVaultHost())
103
+ return true;
101
104
  return (await this.#options.isCustodyActive?.()) ?? true;
102
105
  }
103
106
  #wait(pending, signal) {
@@ -153,7 +156,9 @@ export class ClaustrumConsumer {
153
156
  #boundedConnect(attempt) {
154
157
  const setTimer = this.#options.setTimeoutImpl ?? setTimeout;
155
158
  const clearTimer = this.#options.clearTimeoutImpl ?? clearTimeout;
156
- const pending = this.#options.connect().then((client) => {
159
+ const pending = (!hasVaultHost() && this.#options.connect
160
+ ? this.#options.connect()
161
+ : Promise.resolve().then(() => connectVaultHost(this.#options.pluginId))).then((client) => {
157
162
  if (this.#shutdown.signal.aborted || attempt.timedOut) {
158
163
  client.close();
159
164
  if (!attempt.timedOut)
@@ -429,7 +434,8 @@ export class ClaustrumConsumer {
429
434
  !(await this.#active()))
430
435
  return;
431
436
  try {
432
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
437
+ if (!hasVaultHost())
438
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
433
439
  await this.#getCustody();
434
440
  await this.#insula?.source.refresh((this.#options.now ?? Date.now)());
435
441
  }
@@ -449,7 +455,8 @@ export class ClaustrumConsumer {
449
455
  !(await this.#active()))
450
456
  return undefined;
451
457
  try {
452
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
458
+ if (!hasVaultHost())
459
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
453
460
  return this.#normalizeInsulaQuota(receipt.assertedAccountIdentity);
454
461
  }
455
462
  catch {
@@ -467,7 +474,8 @@ export class ClaustrumConsumer {
467
474
  !(await this.#active()))
468
475
  return undefined;
469
476
  try {
470
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
477
+ if (!hasVaultHost())
478
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
471
479
  const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
472
480
  const row = roster?.rows.find((entry) => entry.routeId === routeId);
473
481
  return this.#normalizeInsulaQuota(row?.accountIdentity);
@@ -482,7 +490,8 @@ export class ClaustrumConsumer {
482
490
  if (!options || this.#shutdown.signal.aborted || !(await this.#active()))
483
491
  return { miss: 'unreachable' };
484
492
  try {
485
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
493
+ if (!hasVaultHost())
494
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
486
495
  const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
487
496
  const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
488
497
  if (!account || !this.#insula)
@@ -249,16 +249,19 @@ export declare const SERVING_MARGIN_MS = 300000;
249
249
  export declare const KEPT_RECEIPT_MARGIN_MS = 60000;
250
250
  /**
251
251
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
252
- * enrollment token as authorization. Used by every host of a plugin. Every
253
- * physical send asks the vault first while reachable. Only an unreachable vault permits
254
- * reuse of the last validated receipt, in memory and bounded by its expiry.
255
- * The enrollment token is re-read per operation so revocation and disconnect
256
- * still take effect without a process restart.
252
+ * enrollment token or the host's grant as authorization. Used by every host of a
253
+ * plugin. Every physical send asks the vault first while reachable. Only an
254
+ * unreachable vault permits reuse of the last validated receipt, in memory and
255
+ * bounded by its expiry. Outside host authority the enrollment token is re-read
256
+ * per operation so revocation and disconnect still take effect without a restart.
257
257
  */
258
258
  export declare class ClaustrumScopedCustody {
259
259
  #private;
260
260
  constructor(options: {
261
- client: ClaustrumScopedClient;
261
+ /** While hosted, only a client returned by connectVaultHost is accepted. */
262
+ client?: ClaustrumScopedClient;
263
+ /** Enrollment-name prefix, required when using the default host client. */
264
+ pluginId?: string;
262
265
  family: ClaustrumFamilyInput;
263
266
  tokenPath?: string;
264
267
  readToken?: () => Promise<EnrollmentTokenFile>;
@@ -309,8 +312,8 @@ export declare class ClaustrumScopedCustody {
309
312
  * Report that a send this consumer actually made was rejected. Only a 401
310
313
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
311
314
  * credential id with the exact record version that send was served, and
312
- * signed with the enrollment token that authorized it. A receipt this
313
- * custody did not issue is refused rather than reported.
315
+ * sent through the client and enrollment token that authorized it. A receipt
316
+ * this custody did not issue is refused rather than reported.
314
317
  */
315
318
  reportFailure(attempt: ClaustrumScopedAttempt, status: number, reporterSource: ClaustrumReporterSource): Promise<void>;
316
319
  /**
@@ -4,6 +4,7 @@ import { createLogger } from '../logger/index.js';
4
4
  import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability.js';
5
5
  import { readClaustrumEnrollmentToken } from './enrollment.js';
6
6
  import { ClaustrumConsumerError } from './errors.js';
7
+ import { connectVaultHost, hasVaultHost, isVaultHostClient } from './host.js';
7
8
  import { CUSTODY_PLACEHOLDER_PREFIX } from './host-slot.js';
8
9
  import { drainShutdown, shutdownWarning } from './shutdown.js';
9
10
  import { ScopedUsageReporter, } from './usage.js';
@@ -174,11 +175,11 @@ function grantReachOf(listed) {
174
175
  }
175
176
  /**
176
177
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
177
- * enrollment token as authorization. Used by every host of a plugin. Every
178
- * physical send asks the vault first while reachable. Only an unreachable vault permits
179
- * reuse of the last validated receipt, in memory and bounded by its expiry.
180
- * The enrollment token is re-read per operation so revocation and disconnect
181
- * still take effect without a process restart.
178
+ * enrollment token or the host's grant as authorization. Used by every host of a
179
+ * plugin. Every physical send asks the vault first while reachable. Only an
180
+ * unreachable vault permits reuse of the last validated receipt, in memory and
181
+ * bounded by its expiry. Outside host authority the enrollment token is re-read
182
+ * per operation so revocation and disconnect still take effect without a restart.
182
183
  */
183
184
  export class ClaustrumScopedCustody {
184
185
  #client;
@@ -211,6 +212,8 @@ export class ClaustrumScopedCustody {
211
212
  #onDrainTimeout;
212
213
  #disposing;
213
214
  constructor(options) {
215
+ if (hasVaultHost() && options.client && !isVaultHostClient(options.client))
216
+ throw new ClaustrumUnreachableError();
214
217
  const tokenPath = options.tokenPath;
215
218
  if (options.readToken) {
216
219
  this.#readToken = options.readToken;
@@ -218,10 +221,15 @@ export class ClaustrumScopedCustody {
218
221
  else if (tokenPath) {
219
222
  this.#readToken = () => readClaustrumEnrollmentToken(tokenPath);
220
223
  }
224
+ else if (hasVaultHost()) {
225
+ this.#readToken = async () => {
226
+ throw new ClaustrumConsumerError('not-enrolled', 'Claustrum enrollment token path is required');
227
+ };
228
+ }
221
229
  else {
222
230
  throw new ClaustrumConsumerError('not-enrolled', 'Claustrum enrollment token path is required');
223
231
  }
224
- this.#client = options.client;
232
+ this.#client = options.client ?? connectVaultHost(options.pluginId);
225
233
  this.#family = options.family;
226
234
  this.#parseIdentity = options.parseIdentity;
227
235
  this.#requireAssertion = options.requireAssertion ?? false;
@@ -233,7 +241,7 @@ export class ClaustrumScopedCustody {
233
241
  this.#usage = new ScopedUsageReporter({
234
242
  client: this.#client,
235
243
  owns: (id) => this.#usageServed.has(id),
236
- token: async () => checkedEnrollmentToken(await this.#readToken()),
244
+ token: async () => hasVaultHost() ? '' : checkedEnrollmentToken(await this.#readToken()),
237
245
  logger: this.#logger,
238
246
  setTimeout: this.#setTimeout,
239
247
  clearTimeout: this.#clearTimeout,
@@ -303,6 +311,9 @@ export class ClaustrumScopedCustody {
303
311
  }
304
312
  async #token(signal) {
305
313
  this.#check(signal);
314
+ // The host ignores this empty argument; it never reaches a vault as a token.
315
+ if (hasVaultHost())
316
+ return '';
306
317
  if (phaseDiagnostics.hasSubscribers)
307
318
  phaseDiagnostics.publish({
308
319
  logger: this.#logger,
@@ -592,7 +603,7 @@ export class ClaustrumScopedCustody {
592
603
  if (kept.since === null)
593
604
  kept.since = this.#now();
594
605
  const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
595
- this.#provenance.set(attempt, token);
606
+ this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token, client: this.#client });
596
607
  this.#keptAttempts.set(attempt, routeId);
597
608
  return attempt;
598
609
  }
@@ -673,22 +684,22 @@ export class ClaustrumScopedCustody {
673
684
  recordVersion: served.recordVersion,
674
685
  expiresAtMs,
675
686
  }, 'accessToken', { value: accessToken, enumerable: false }));
676
- this.#provenance.set(attempt, token);
687
+ this.#provenance.set(attempt, { token, client: this.#client });
677
688
  return attempt;
678
689
  }
679
690
  /**
680
691
  * Report that a send this consumer actually made was rejected. Only a 401
681
692
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
682
693
  * credential id with the exact record version that send was served, and
683
- * signed with the enrollment token that authorized it. A receipt this
684
- * custody did not issue is refused rather than reported.
694
+ * sent through the client and enrollment token that authorized it. A receipt
695
+ * this custody did not issue is refused rather than reported.
685
696
  */
686
697
  async reportFailure(attempt, status, reporterSource) {
687
698
  if (status !== 401)
688
699
  return;
689
700
  this.#check();
690
- const token = this.#provenance.get(attempt);
691
- if (!token)
701
+ const provenance = this.#provenance.get(attempt);
702
+ if (!provenance)
692
703
  throw new ClaustrumConsumerError('no-receipt', 'Claustrum failure report requires an original dispatch receipt');
693
704
  const keptRoute = this.#keptAttempts.get(attempt);
694
705
  if (keptRoute !== undefined) {
@@ -708,9 +719,9 @@ export class ClaustrumScopedCustody {
708
719
  const pending = this.#reports.get(attempt);
709
720
  if (pending)
710
721
  return pending;
711
- const report = this.#call(() => this.#client.reportAuthFailureScoped({
722
+ const report = this.#call(() => provenance.client.reportAuthFailureScoped({
712
723
  credentialId: attempt.credentialId,
713
- enrollmentToken: token,
724
+ enrollmentToken: provenance.token,
714
725
  providerStatus: 401,
715
726
  recordVersion: attempt.recordVersion,
716
727
  reporterSource,
@@ -124,6 +124,8 @@ export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollment
124
124
  * owner-only, as every private-file read there does.
125
125
  */
126
126
  export declare function enrollmentAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'vault' | 'local' | 'unreadable'>;
127
+ /** Host authority takes precedence without reading any plugin enrollment files. */
128
+ export declare function vaultAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'host' | 'vault' | 'local' | 'unreadable'>;
127
129
  /**
128
130
  * Read fresh bearer material for one scoped operation; never publish it.
129
131
  * Re-reading per operation is what lets an operator reissue a token on disk.
@@ -7,6 +7,7 @@ import { FileReadCache } from '../fs/file-read-cache.js';
7
7
  import { acquireRefreshFileLock } from '../fs/index.js';
8
8
  import { ensurePrivateDirectory as ensureWindowsDirectory, PrivateFileError, readPrivateText, verifySafeDirectory, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
9
9
  import { ClaustrumConsumerError } from './errors.js';
10
+ import { hasVaultHost } from './host.js';
10
11
  const ENROLLMENT_SCHEMA = 1;
11
12
  const ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
12
13
  const ENROLLMENT_LOCK_TTL_MS = 30_000;
@@ -500,6 +501,12 @@ export async function enrollmentAuthority(paths, proposedName) {
500
501
  }
501
502
  return 'local';
502
503
  }
504
+ /** Host authority takes precedence without reading any plugin enrollment files. */
505
+ export async function vaultAuthority(paths, proposedName) {
506
+ if (hasVaultHost())
507
+ return 'host';
508
+ return enrollmentAuthority(paths, proposedName);
509
+ }
503
510
  /**
504
511
  * Read fresh bearer material for one scoped operation; never publish it.
505
512
  * Re-reading per operation is what lets an operator reissue a token on disk.
@@ -0,0 +1,8 @@
1
+ import type { ClaustrumScopedClient } from './custody.js';
2
+ export declare const VAULT_HOST_STATUS = "Served by Thalamus";
3
+ export declare const VAULT_HOST_CONNECT_REFUSAL = "This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.";
4
+ export declare function isVaultHostClient(client: ClaustrumScopedClient): boolean;
5
+ /** The spawn marker, not a global installed by another plugin, selects authority. */
6
+ export declare function hasVaultHost(): boolean;
7
+ /** Read at connect time so a bridge installed after the auth plugin can recover. */
8
+ export declare function connectVaultHost(pluginId?: string): ClaustrumScopedClient;
@@ -0,0 +1,113 @@
1
+ import { ClaustrumCredentialError } from '@cortexkit/claustrum-client';
2
+ import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability.js';
3
+ export const VAULT_HOST_STATUS = 'Served by Thalamus';
4
+ export const VAULT_HOST_CONNECT_REFUSAL = "This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.";
5
+ // Object identity prevents a native client from carrying the host's empty token argument.
6
+ const hostClients = new WeakSet();
7
+ export function isVaultHostClient(client) {
8
+ return hostClients.has(client);
9
+ }
10
+ /** The spawn marker, not a global installed by another plugin, selects authority. */
11
+ export function hasVaultHost() {
12
+ return process.env.CORTEXKIT_VAULT_HOST === 'thalamus';
13
+ }
14
+ function hostError(error) {
15
+ if (typeof error !== 'object' || error === null)
16
+ return error;
17
+ const value = error;
18
+ if (typeof value.code === 'string' &&
19
+ (value.class === 'transient' ||
20
+ value.class === 'permanent' ||
21
+ value.class === 'auth_required' ||
22
+ value.class === 'context_overflow') &&
23
+ (value.action === 'gone' ||
24
+ value.action === 'reauth' ||
25
+ value.action === 'retry' ||
26
+ value.action === 'reduce_and_retry'))
27
+ return new ClaustrumCredentialError(value.code, value.class, value.action);
28
+ if (value.name === 'ClaustrumUnreachableError' ||
29
+ (typeof value.code === 'string' &&
30
+ classifyVaultFailure(Object.assign(new Error(), { code: value.code })) ===
31
+ 'unreachable'))
32
+ return new ClaustrumUnreachableError();
33
+ return error;
34
+ }
35
+ function call(operation) {
36
+ try {
37
+ return operation();
38
+ }
39
+ catch (error) {
40
+ throw hostError(error);
41
+ }
42
+ }
43
+ async function request(operation) {
44
+ try {
45
+ return await operation();
46
+ }
47
+ catch (error) {
48
+ throw hostError(error);
49
+ }
50
+ }
51
+ /** Normalize only the host boundary; native clients keep their strict error identity. */
52
+ function wrapHostClient(client) {
53
+ const watchScoped = client.watchScoped?.bind(client);
54
+ const reportUsageScoped = client.reportUsageScoped?.bind(client);
55
+ return {
56
+ listScoped: (...args) => request(() => client.listScoped(...args)),
57
+ getScoped: (...args) => request(() => client.getScoped(...args)),
58
+ reportAuthFailureScoped: (...args) => request(() => client.reportAuthFailureScoped(...args)),
59
+ close: () => call(() => client.close()),
60
+ ...(watchScoped && {
61
+ watchScoped: (...args) => {
62
+ const watch = call(() => watchScoped(...args));
63
+ return {
64
+ stop: () => call(() => watch.stop()),
65
+ closed: request(async () => {
66
+ const end = await watch.closed;
67
+ return end.kind === 'refused' || end.kind === 'transport_lost'
68
+ ? { ...end, error: hostError(end.error) }
69
+ : end;
70
+ }),
71
+ };
72
+ },
73
+ }),
74
+ ...(reportUsageScoped && {
75
+ reportUsageScoped: (...args) => request(() => reportUsageScoped(...args)),
76
+ }),
77
+ ...(client.insula && {
78
+ insula: wrapInsula(client.insula),
79
+ }),
80
+ };
81
+ }
82
+ function wrapInsula(transport) {
83
+ const watchUsage = transport.watchUsage?.bind(transport);
84
+ return {
85
+ connectionFile: transport.connectionFile,
86
+ getUsage: () => request(() => transport.getUsage()),
87
+ ...(watchUsage && {
88
+ watchUsage: (...args) => {
89
+ const watch = call(() => watchUsage(...args));
90
+ return {
91
+ stop: () => call(() => watch.stop()),
92
+ closed: request(() => watch.closed),
93
+ };
94
+ },
95
+ }),
96
+ };
97
+ }
98
+ /** Read at connect time so a bridge installed after the auth plugin can recover. */
99
+ export function connectVaultHost(pluginId) {
100
+ if (!hasVaultHost() || !pluginId)
101
+ throw new ClaustrumUnreachableError();
102
+ try {
103
+ const accessor = globalThis[Symbol.for('cortexkit.vault')];
104
+ if (typeof accessor !== 'function')
105
+ throw new ClaustrumUnreachableError();
106
+ const client = wrapHostClient(accessor(pluginId));
107
+ hostClients.add(client);
108
+ return client;
109
+ }
110
+ catch {
111
+ throw new ClaustrumUnreachableError();
112
+ }
113
+ }
@@ -46,7 +46,10 @@ export interface ClaustrumDiscoveryHubOptions {
46
46
  * member for any row and is refused.
47
47
  */
48
48
  family: ClassifyingClaustrumFamily<string>;
49
- connect: () => Promise<ClaustrumScopedClient>;
49
+ /** Enrollment-name prefix, required by the default host connection. */
50
+ pluginId?: string;
51
+ /** Used outside host authority; hosted connections always use the relay. */
52
+ connect?: () => Promise<ClaustrumScopedClient>;
50
53
  /**
51
54
  * How long one `connect()` attempt may take before the hub treats the vault
52
55
  * as unreachable (default 10 s, as `ClaustrumConsumerOptions`). The hub's
@@ -60,6 +63,7 @@ export interface ClaustrumDiscoveryHubOptions {
60
63
  * state only, never from the vault: on every hub tick, and when a member
61
64
  * refreshes or authorizes. The first false read revokes every lease,
62
65
  * closes the connection and clears every member.
66
+ * Host authority always selects custody and does not call this callback.
63
67
  */
64
68
  isCustodyActive?: () => boolean | Promise<boolean>;
65
69
  parseIdentity?: IdentityParser;
@@ -21,6 +21,7 @@ import { createHubMember, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
21
21
  import { ClaustrumScopedCustody, } from './custody.js';
22
22
  import { ensureClaustrumPrivateDirectory } from './enrollment.js';
23
23
  import { ClaustrumConsumerError } from './errors.js';
24
+ import { connectVaultHost, hasVaultHost } from './host.js';
24
25
  import { DEFAULT_ROUTE_PREFIX, decodedVaultRoster, forgetPendingVaultDiscovery, isVaultRosterLockRefusal, readVaultRoster, refreshVaultRoster, vaultRosterSeed, } from './roster.js';
25
26
  import { drainShutdown, shutdownWarning } from './shutdown.js';
26
27
  import { SAFETY_POLL_MS } from './watch.js';
@@ -383,7 +384,9 @@ export class ClaustrumDiscoveryHub {
383
384
  // that never settles would otherwise hold them all for the hub's life.
384
385
  const connectTimeoutMs = this.#options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
385
386
  let timer;
386
- const connect = this.#options.connect().then((client) => {
387
+ const connect = (!hasVaultHost() && this.#options.connect
388
+ ? this.#options.connect()
389
+ : Promise.resolve().then(() => connectVaultHost(this.#options.pluginId))).then((client) => {
387
390
  // A connect resolves into its generation only while that generation
388
391
  // is current and still wanted; otherwise its client never serves.
389
392
  if (entry.timedOut) {
@@ -567,7 +570,7 @@ export class ClaustrumDiscoveryHub {
567
570
  * runs the inactive transition; nothing else does.
568
571
  */
569
572
  async #readAuthority() {
570
- const active = (await this.#options.isCustodyActive?.()) ?? true;
573
+ const active = hasVaultHost() || ((await this.#options.isCustodyActive?.()) ?? true);
571
574
  if (this.#shutdown.signal.aborted)
572
575
  return false;
573
576
  const was = this.#active;
@@ -4,8 +4,9 @@ export { ClaustrumCredentialError, type ClaustrumReporterSource, type Enrollment
4
4
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
5
5
  export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, DEFAULT_CONNECT_TIMEOUT_MS, type SendOptions, } from './consumer.js';
6
6
  export { type AccountIdentitySource, type ClassifyingClaustrumFamily, type ClaustrumFamily, type ClaustrumFamilyInput, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, type VaultRowFacts, } from './custody.js';
7
- 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
+ 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, vaultAuthority, } from './enrollment.js';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
+ export { connectVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
9
10
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
10
11
  export { ClaustrumDiscoveryHub, type ClaustrumDiscoveryHubOptions, type ClaustrumHubMemberOptions, type ClaustrumHubRefusals, type ClaustrumLeasedCustody, type CustodyLease, } from './hub.js';
11
12
  export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaLookup, type InsulaQuotaMiss, type InsulaQuotaOptions, type InsulaQuotaReading, type InsulaQuotaResult, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } from './insula.js';
@@ -10,8 +10,9 @@ export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
10
10
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from './availability.js';
11
11
  export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
12
12
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from './custody.js';
13
- export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
13
+ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, vaultAuthority, } from './enrollment.js';
14
14
  export { ClaustrumConsumerError, } from './errors.js';
15
+ export { connectVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
15
16
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
16
17
  export { ClaustrumDiscoveryHub, } from './hub.js';
17
18
  export { acquireInsulaQuotaSource, } from './insula.js';
@@ -290,6 +290,27 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
290
290
  }
291
291
  }));
292
292
  };
293
+ const emitRetry = async (payload) => {
294
+ const transports = new Set([...attempts.values()]
295
+ .filter((rec) => rec.scope.sessionID === payload.sessionID)
296
+ .map((rec) => rec.transport)
297
+ .filter((transport) => transport !== undefined));
298
+ const transport = payload.handle?.transport ??
299
+ (transports.size === 1 ? [...transports][0] : 'unknown');
300
+ try {
301
+ logger?.info?.('opencode2 auth retry decision', {
302
+ sessionID: payload.sessionID,
303
+ transport,
304
+ attempt: payload.attempt,
305
+ reason: payload.reason === 'host-decides' && mixed(payload.sessionID)
306
+ ? 'mixed-session'
307
+ : payload.reason,
308
+ retry: payload.decision.retry,
309
+ });
310
+ }
311
+ catch { }
312
+ await emit('retry', payload);
313
+ };
293
314
  const deliverEnd = async (attempt, outcome) => {
294
315
  try {
295
316
  await adapter.onAttemptEnd?.(attempt, outcome);
@@ -805,7 +826,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
805
826
  }
806
827
  response = new Response(trackBody(body, (error) => {
807
828
  if (error?.reason === 'failed')
808
- rec.httpReadFailed = true;
829
+ rec.readFailed = true;
809
830
  finish(rec, error);
810
831
  }), {
811
832
  status: original.status,
@@ -915,7 +936,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
915
936
  if (ownership && latestTransportOwned.get(draft.sessionID) !== true)
916
937
  return;
917
938
  const hostDecision = draft.decision;
918
- const hostDecides = () => emit('retry', {
939
+ const hostDecides = () => emitRetry({
919
940
  sessionID: draft.sessionID,
920
941
  attempt: draft.attempt,
921
942
  reason: 'host-decides',
@@ -932,7 +953,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
932
953
  if (picked === 'ambiguous') {
933
954
  // Nothing tells which open attempt failed: keep the host's
934
955
  // decision and leave every attempt as it is.
935
- await emit('retry', {
956
+ await emitRetry({
936
957
  sessionID: draft.sessionID,
937
958
  attempt: draft.attempt,
938
959
  reason: 'host-decides',
@@ -948,8 +969,18 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
948
969
  const retrySameAccount = adapter.retrySameAccount?.bind(adapter);
949
970
  const handle = rec.attempt;
950
971
  const afterOutput = rec.outputStarted;
972
+ if (rec.transport === 'ws' &&
973
+ afterOutput &&
974
+ !rec.ended &&
975
+ !rec.limit &&
976
+ !(rec.status !== undefined && rec.status >= 400) &&
977
+ !(draft.error.status !== undefined && draft.error.status >= 400) &&
978
+ draft.error.type === 'provider.transport') {
979
+ rec.readFailed = true;
980
+ finish(rec, { reason: 'failed', message: draft.error.message });
981
+ }
951
982
  if (afterOutput &&
952
- rec.httpReadFailed &&
983
+ rec.readFailed &&
953
984
  retrySameAccount &&
954
985
  handle &&
955
986
  !mixed(draft.sessionID)) {
@@ -964,9 +995,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
964
995
  await rec.limit.delivered;
965
996
  checkRetryActive();
966
997
  }
967
- // The host drops read-operation metadata from its retry error. Only
968
- // our attributed body reader can prove a read failed; wording cannot.
969
- const canContinue = () => rec.httpReadFailed === true &&
998
+ // The host drops read-operation metadata from its retry error. HTTP
999
+ // needs our body reader's failure; WebSocket needs inspected output
1000
+ // without a terminal frame, since the host only sends before reading.
1001
+ // Ending the socket attempt above also excludes any late frames.
1002
+ const canContinue = () => rec.readFailed === true &&
970
1003
  draft.error.type === 'provider.transport' &&
971
1004
  hostDecision.retry &&
972
1005
  hostRetryLimit - draft.attempt >= 1 &&
@@ -1072,7 +1105,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1072
1105
  });
1073
1106
  checkRetryActive();
1074
1107
  if (retried) {
1075
- await emit('retry', {
1108
+ await emitRetry({
1076
1109
  sessionID: draft.sessionID,
1077
1110
  accountId: rec.accountId,
1078
1111
  kind: rec.scope.kind,
@@ -1327,7 +1360,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1327
1360
  return { decision, reason };
1328
1361
  });
1329
1362
  checkRetryActive();
1330
- await emit('retry', {
1363
+ await emitRetry({
1331
1364
  sessionID: draft.sessionID,
1332
1365
  ...(rec.accountId === undefined
1333
1366
  ? {}
@@ -487,6 +487,8 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
487
487
  }
488
488
  export interface OpenCode2AuthLogger {
489
489
  warn(message: string, data?: unknown): void;
490
+ /** Retry decisions, without account details or provider error contents. */
491
+ info?(message: string, data?: unknown): void;
490
492
  }
491
493
  export interface InstallOpenCode2AuthOptions {
492
494
  /**
@@ -541,7 +543,7 @@ export interface InstallOpenCode2AuthOptions {
541
543
  * - `reroute`: refused for a limit before any output, and `chooseAccount`
542
544
  * named another account for the next attempt, so the host retries at once;
543
545
  * - `output-started`: output reached the user without a safe continuation, so no retry;
544
- * - `continue-same-account`: a witnessed HTTP read failure after output, with
546
+ * - `continue-same-account`: a witnessed transport read failure after output, with
545
547
  * adapter-approved identity preservation; keeps the host's continuation and delay;
546
548
  * - `no-account`: the attempt had no account, so no retry;
547
549
  * - `host-decides-last-account`: refused for a limit before any output, but
@@ -1,6 +1,7 @@
1
1
  import { select } from '../auth-menu/select.js';
2
2
  import { isInteractive, printLine, processTerminal, } from '../auth-menu/terminal.js';
3
- import { enrollmentAuthority, hostEnrollmentPaths, } from '../claustrum/enrollment.js';
3
+ import { hostEnrollmentPaths, vaultAuthority } from '../claustrum/enrollment.js';
4
+ import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
4
5
  import { recordSetupEnrollment, setupEnrollmentLine } from './command-error.js';
5
6
  import { defaultCommandRunner } from './command-runner.js';
6
7
  import { detectHosts } from './detect.js';
@@ -27,7 +28,7 @@ function validatePlugin(plugin) {
27
28
  * Turn what setup recorded into one outcome per selected host, in setup order.
28
29
  * A host setup never reached was never asked to enroll. Only a host whose
29
30
  * enrollment was in flight when setup failed is checked on disk, by reading its
30
- * enrollment files once with `enrollmentAuthority`; if that read fails it stays
31
+ * authority once with `vaultAuthority`; if that read fails it stays
31
32
  * `unknown`.
32
33
  */
33
34
  async function enrollmentReport(plugin, hosts, recorded) {
@@ -36,8 +37,8 @@ async function enrollmentReport(plugin, hosts, recorded) {
36
37
  let outcome = recorded.get(host) ?? 'not-enrolled';
37
38
  if (outcome === 'unknown') {
38
39
  const { name, paths } = plugin.vault.hosts[host];
39
- const authority = await enrollmentAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
40
- if (authority === 'vault')
40
+ const authority = await vaultAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
41
+ if (authority === 'vault' || authority === 'host')
41
42
  outcome = 'enrolled';
42
43
  else if (authority === 'local')
43
44
  outcome = 'not-enrolled';
@@ -48,6 +49,9 @@ async function enrollmentReport(plugin, hosts, recorded) {
48
49
  }
49
50
  export async function runSetup(plugin, argv = [], io = {}) {
50
51
  const options = parseSetupFlags(argv);
52
+ // Hosted sign-in belongs to Thalamus, never to a plugin's local setup.
53
+ if (hasVaultHost())
54
+ throw new Error(VAULT_HOST_CONNECT_REFUSAL);
51
55
  validatePlugin(plugin);
52
56
  const terminal = io.terminal ?? processTerminal();
53
57
  const detection = await detectHosts(plugin, io);
@@ -2,6 +2,7 @@ import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
3
3
  import { printLine } from '../auth-menu/terminal.js';
4
4
  import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, UNSUPPORTED_ENROLLMENT_CODE, } from '../claustrum/enrollment.js';
5
+ import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
5
6
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
7
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
7
8
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
@@ -51,6 +52,8 @@ function approveCommand(requestId, name) {
51
52
  }
52
53
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
53
54
  export async function connectSetupHost(plugin, host, io, terminal, fence) {
55
+ if (hasVaultHost())
56
+ throw new Error(VAULT_HOST_CONNECT_REFUSAL);
54
57
  const { name, paths: input } = plugin.vault.hosts[host];
55
58
  const paths = hostEnrollmentPaths(input);
56
59
  await fence();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.39.1",
3
+ "version": "0.40.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": {