@cortexkit/common-auth 0.43.0 → 0.44.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,4 +1,4 @@
1
- import { type ClaustrumClientOptions as ClaustrumEnrollmentClientOptions, type EnrollmentPollOutcome, type EnrollmentTokenFile, writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
1
+ import { type ClaustrumClientOptions as ClaustrumEnrollmentClientOptions, ClaustrumClient as ClaustrumWireClient, type EnrollmentPollOutcome, type EnrollmentTokenFile, writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
2
2
  /**
3
3
  * The code a vault without the enrollment ceremony answers a proposal with.
4
4
  * Setup reports it as "this vault cannot connect plugins" instead of waiting.
@@ -31,11 +31,29 @@ export declare function classifyEnrollmentError(error: unknown): {
31
31
  export declare function enrollmentName(plugin: string, host: string): string;
32
32
  /** Match the vault's plain-text, code-point limit before proposing a display name. */
33
33
  export declare function validEnrollmentDisplayName(displayName: string): boolean;
34
+ export type ClaustrumRequestedGrant = {
35
+ selector: {
36
+ category: string;
37
+ exact?: never;
38
+ } | {
39
+ exact: string;
40
+ category?: never;
41
+ };
42
+ operation: 'read' | 'list';
43
+ };
44
+ /** Reject malformed permissions before a compatibility retry can omit them. */
45
+ export declare function validEnrollmentRequestedGrants(grants: unknown): grants is ReadonlyArray<ClaustrumRequestedGrant>;
46
+ interface EnrollmentGrantProposal {
47
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
48
+ /** Sent is not proof of access: the operator can approve without grants. */
49
+ requestedGrantsStatus?: 'sent' | 'dropped';
50
+ }
34
51
  export interface ClaustrumEnrollmentClient {
35
52
  enrollPropose(input: {
36
53
  name: string;
37
54
  requestSecretHash: string;
38
55
  displayName?: string;
56
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
39
57
  }): Promise<{
40
58
  requestId: string;
41
59
  }>;
@@ -46,6 +64,7 @@ export interface ClaustrumEnrollmentClient {
46
64
  }
47
65
  export interface ClaustrumEnrollmentConnection extends ClaustrumEnrollmentClient {
48
66
  close(): void;
67
+ listScoped?: ClaustrumWireClient['listScoped'];
49
68
  }
50
69
  /**
51
70
  * Connect the enrollment ceremony. Setup calls this; the request path never
@@ -57,17 +76,17 @@ export declare function connectClaustrumEnrollmentClient(options: ClaustrumEnrol
57
76
  }): Promise<ClaustrumEnrollmentConnection>;
58
77
  export type ClaustrumEnrollmentStatus = {
59
78
  state: 'idle';
60
- } | {
79
+ } | (EnrollmentGrantProposal & {
61
80
  state: 'pending';
62
81
  proposedName: string;
63
82
  requestId?: string;
64
83
  retryCode?: string;
65
- } | {
84
+ }) | (EnrollmentGrantProposal & {
66
85
  state: 'approved';
67
86
  proposedName: string;
68
87
  approvedName?: string;
69
88
  tokenGeneration: number;
70
- } | {
89
+ }) | {
71
90
  state: 'denied';
72
91
  proposedName: string;
73
92
  } | {
@@ -146,6 +165,7 @@ export declare class ClaustrumEnrollmentManager {
146
165
  paths: ClaustrumEnrollmentPaths;
147
166
  proposedName: string;
148
167
  displayName?: string;
168
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
149
169
  now?: () => number;
150
170
  mintSecret?: () => string;
151
171
  writeTokenFile?: typeof writeEnrollmentTokenFile;
@@ -182,3 +202,4 @@ export type ClaustrumEnrollmentDisconnectResult = 'disconnected' | 'idle' | 'bus
182
202
  * wrong owner, not owner-only) refuses with `unsafe-file` and both files stay.
183
203
  */
184
204
  export declare function disconnectClaustrumEnrollment(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentDisconnectResult>;
205
+ export {};
@@ -75,6 +75,35 @@ export function validEnrollmentDisplayName(displayName) {
75
75
  length <= 40 &&
76
76
  !/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test(displayName));
77
77
  }
78
+ /** Reject malformed permissions before a compatibility retry can omit them. */
79
+ export function validEnrollmentRequestedGrants(grants) {
80
+ return (Array.isArray(grants) &&
81
+ grants.length >= 1 &&
82
+ grants.length <= 4 &&
83
+ Array.from(grants).every((grant) => {
84
+ if (!isRecord(grant) ||
85
+ Object.keys(grant).length !== 2 ||
86
+ (grant.operation !== 'read' && grant.operation !== 'list') ||
87
+ !isRecord(grant.selector))
88
+ return false;
89
+ const keys = Object.keys(grant.selector);
90
+ const key = keys[0];
91
+ return (keys.length === 1 &&
92
+ (key === 'category' || key === 'exact') &&
93
+ typeof grant.selector[key] === 'string' &&
94
+ grant.selector[key].trim().length > 0);
95
+ }));
96
+ }
97
+ function grantProposal(state) {
98
+ return {
99
+ ...(state.requestedGrants !== undefined && {
100
+ requestedGrants: state.requestedGrants,
101
+ }),
102
+ ...(state.requestedGrantsStatus !== undefined && {
103
+ requestedGrantsStatus: state.requestedGrantsStatus,
104
+ }),
105
+ };
106
+ }
78
107
  /**
79
108
  * Connect the enrollment ceremony. Setup calls this; the request path never
80
109
  * does. `connectionFile` is required because this library reads no
@@ -129,6 +158,7 @@ function decodeEnrollmentState(value) {
129
158
  throw invalidState();
130
159
  }
131
160
  if (value.phase === 'pending') {
161
+ const grants = decodeGrantProposal(value);
132
162
  if (!TOKEN_RE.test(String(value.requestSecret ?? '')) ||
133
163
  (value.requestId !== undefined &&
134
164
  (typeof value.requestId !== 'string' ||
@@ -147,9 +177,11 @@ function decodeEnrollmentState(value) {
147
177
  }),
148
178
  createdAt: value.createdAt,
149
179
  updatedAt: value.updatedAt,
180
+ ...grants,
150
181
  };
151
182
  }
152
183
  if (value.phase === 'approved') {
184
+ const grants = decodeGrantProposal(value);
153
185
  if ((value.approvedName !== undefined &&
154
186
  (typeof value.approvedName !== 'string' ||
155
187
  value.approvedName.length === 0)) ||
@@ -166,6 +198,7 @@ function decodeEnrollmentState(value) {
166
198
  }),
167
199
  tokenGeneration: value.tokenGeneration,
168
200
  updatedAt: value.updatedAt,
201
+ ...grants,
169
202
  };
170
203
  }
171
204
  if (value.phase === 'denied' || value.phase === 'blocked') {
@@ -185,6 +218,18 @@ function decodeEnrollmentState(value) {
185
218
  }
186
219
  throw invalidState();
187
220
  }
221
+ function decodeGrantProposal(value) {
222
+ // Optional proposal metadata from a newer version must not invalidate an
223
+ // existing enrollment when a plugin is downgraded. Never infer access from it.
224
+ if ((value.requestedGrants !== undefined &&
225
+ !validEnrollmentRequestedGrants(value.requestedGrants)) ||
226
+ (value.requestedGrantsStatus !== undefined &&
227
+ (value.requestedGrants === undefined ||
228
+ (value.requestedGrantsStatus !== 'sent' &&
229
+ value.requestedGrantsStatus !== 'dropped'))))
230
+ return {};
231
+ return grantProposal(value);
232
+ }
188
233
  function decodeTokenFile(value) {
189
234
  if (!isRecord(value) ||
190
235
  !TOKEN_RE.test(String(value.token ?? '')) ||
@@ -452,6 +497,9 @@ async function readEnrollmentStatus(paths, proposedName) {
452
497
  approvedName: state.approvedName,
453
498
  }),
454
499
  tokenGeneration: token.token_generation,
500
+ ...(state &&
501
+ (state.phase === 'approved' || state.phase === 'pending') &&
502
+ grantProposal(state)),
455
503
  },
456
504
  };
457
505
  }
@@ -534,6 +582,7 @@ function statusFromState(state) {
534
582
  state: 'pending',
535
583
  proposedName: state.proposedName,
536
584
  ...(state.requestId !== undefined && { requestId: state.requestId }),
585
+ ...grantProposal(state),
537
586
  };
538
587
  }
539
588
  if (state.phase === 'approved') {
@@ -544,6 +593,7 @@ function statusFromState(state) {
544
593
  approvedName: state.approvedName,
545
594
  }),
546
595
  tokenGeneration: state.tokenGeneration,
596
+ ...grantProposal(state),
547
597
  };
548
598
  }
549
599
  if (state.phase === 'denied')
@@ -567,6 +617,7 @@ export class ClaustrumEnrollmentManager {
567
617
  #paths;
568
618
  #proposedName;
569
619
  #displayName;
620
+ #requestedGrants;
570
621
  #now;
571
622
  #mintSecret;
572
623
  #writeTokenFile;
@@ -575,6 +626,13 @@ export class ClaustrumEnrollmentManager {
575
626
  if (options.displayName !== undefined &&
576
627
  !validEnrollmentDisplayName(options.displayName))
577
628
  throw new ClaustrumConsumerError('invalid-state', 'invalid Claustrum enrollment display name');
629
+ if (options.requestedGrants !== undefined &&
630
+ !validEnrollmentRequestedGrants(options.requestedGrants))
631
+ throw new ClaustrumConsumerError('invalid-state', 'invalid Claustrum enrollment requested grants');
632
+ this.#requestedGrants = options.requestedGrants?.map((grant) => ({
633
+ selector: { ...grant.selector },
634
+ operation: grant.operation,
635
+ }));
578
636
  this.#ancestorOptions = options.ancestorOptions ?? {};
579
637
  this.#client = options.client;
580
638
  this.#paths = options.paths;
@@ -627,6 +685,7 @@ export class ClaustrumEnrollmentManager {
627
685
  phase: 'approved',
628
686
  proposedName: state?.proposedName ?? this.#proposedName,
629
687
  tokenGeneration: token.token_generation,
688
+ ...(state && grantProposal(state)),
630
689
  updatedAt: this.#now(),
631
690
  };
632
691
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -640,6 +699,7 @@ export class ClaustrumEnrollmentManager {
640
699
  approvedName: state.approvedName,
641
700
  }),
642
701
  tokenGeneration: token.token_generation,
702
+ ...(state.phase === 'approved' && grantProposal(state)),
643
703
  };
644
704
  }
645
705
  if (state?.phase === 'approved') {
@@ -664,6 +724,9 @@ export class ClaustrumEnrollmentManager {
664
724
  requestSecret: this.#mintSecret(),
665
725
  createdAt: now,
666
726
  updatedAt: now,
727
+ ...(this.#requestedGrants !== undefined && {
728
+ requestedGrants: this.#requestedGrants,
729
+ }),
667
730
  };
668
731
  if (!TOKEN_RE.test(state.requestSecret))
669
732
  throw new ClaustrumConsumerError('invalid-state', 'invalid minted Claustrum enrollment secret');
@@ -682,28 +745,39 @@ export class ClaustrumEnrollmentManager {
682
745
  requestSecretHash,
683
746
  };
684
747
  let proposed;
748
+ let requestedGrantsStatus = state.requestedGrantsStatus;
685
749
  try {
686
750
  proposed = await this.#client.enrollPropose({
687
751
  ...proposal,
688
752
  ...(this.#displayName !== undefined && {
689
753
  displayName: this.#displayName,
690
754
  }),
755
+ ...(state.requestedGrants !== undefined && {
756
+ requestedGrants: state.requestedGrants,
757
+ }),
691
758
  });
759
+ if (state.requestedGrants !== undefined)
760
+ requestedGrantsStatus = 'sent';
692
761
  }
693
762
  catch (error) {
694
- if (this.#displayName === undefined ||
763
+ if ((this.#displayName === undefined &&
764
+ state.requestedGrants === undefined) ||
695
765
  !(error instanceof ClaustrumCredentialError) ||
696
766
  error.code !== 'invalid_params')
697
767
  throw error;
698
- // Locally validated names can only be refused by vaults that do
699
- // not support displayName. A refused proposal stores nothing, so
700
- // retry once with the same hash and let normal handling decide.
768
+ // Both optional fields were validated locally. Older vaults reject
769
+ // either field without storing a proposal, so retry the plain shape once.
701
770
  proposed = await this.#client.enrollPropose(proposal);
771
+ if (state.requestedGrants !== undefined)
772
+ requestedGrantsStatus = 'dropped';
702
773
  }
703
774
  state = {
704
775
  ...state,
705
776
  requestId: proposed.requestId,
706
777
  updatedAt: this.#now(),
778
+ ...(requestedGrantsStatus !== undefined && {
779
+ requestedGrantsStatus,
780
+ }),
707
781
  };
708
782
  await writeStateAtomic(this.#paths.statePath, state, this.#ancestorOptions);
709
783
  }
@@ -716,6 +790,7 @@ export class ClaustrumEnrollmentManager {
716
790
  state: 'pending',
717
791
  proposedName: state.proposedName,
718
792
  retryCode: refusal.code,
793
+ ...grantProposal(state),
719
794
  };
720
795
  }
721
796
  // A vault without the ceremony cannot hold a request for this
@@ -772,6 +847,7 @@ export class ClaustrumEnrollmentManager {
772
847
  proposedName: state.proposedName,
773
848
  approvedName: outcome.name,
774
849
  tokenGeneration: outcome.tokenGeneration,
850
+ ...grantProposal(state),
775
851
  updatedAt: this.#now(),
776
852
  };
777
853
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -787,6 +863,7 @@ export class ClaustrumEnrollmentManager {
787
863
  proposedName: state.proposedName,
788
864
  requestId,
789
865
  retryCode: refusal.code,
866
+ ...grantProposal(state),
790
867
  };
791
868
  }
792
869
  return this.#block(state, refusal.code);
@@ -4,7 +4,7 @@ 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, validEnrollmentDisplayName, vaultAuthority, } from './enrollment.js';
7
+ export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, type ClaustrumRequestedGrant, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, validEnrollmentDisplayName, validEnrollmentRequestedGrants, vaultAuthority, } from './enrollment.js';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
9
  export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
10
10
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
@@ -10,7 +10,7 @@ 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, validEnrollmentDisplayName, vaultAuthority, } from './enrollment.js';
13
+ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, validEnrollmentDisplayName, validEnrollmentRequestedGrants, vaultAuthority, } from './enrollment.js';
14
14
  export { ClaustrumConsumerError, } from './errors.js';
15
15
  export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
16
16
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
@@ -17,7 +17,7 @@ export declare class SetupCommandError extends Error {
17
17
  });
18
18
  }
19
19
  /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
20
- export declare function setupEnrollmentLine({ host, outcome, }: SetupHostEnrollment): string;
20
+ export declare function setupEnrollmentLine({ host, outcome, access, }: SetupHostEnrollment): string;
21
21
  /**
22
22
  * Remember which hosts a failed setup left connected to the vault, against the
23
23
  * thrown value. Only objects can carry a record; a thrown primitive is left as
@@ -1,5 +1,6 @@
1
1
  import { redact } from '../logger/redact.js';
2
2
  import { STDERR_TAIL_MAX_BYTES } from './command-runner.js';
3
+ import { enrollmentAccessLines } from './enrollment-access.js';
3
4
  const PI_INSTALL_ERROR_MESSAGE = 'Pi install failed; run pi install after checking your npm connection.';
4
5
  function utf8Tail(value) {
5
6
  const bytes = Buffer.from(value, 'utf8');
@@ -47,8 +48,8 @@ const OUTCOME_TEXT = {
47
48
  unknown: 'unknown, check with ck auth status',
48
49
  };
49
50
  /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
50
- export function setupEnrollmentLine({ host, outcome, }) {
51
- return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
51
+ export function setupEnrollmentLine({ host, outcome, access, }) {
52
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${access ? ` — ${enrollmentAccessLines(access).join('\n')}` : ''}`;
52
53
  }
53
54
  // Outcomes recorded against the value a failed `runSetup` threw. A WeakMap
54
55
  // keeps the thrown value itself untouched: setup never reads, rewrites or
@@ -1,11 +1,12 @@
1
1
  import { select } from '../auth-menu/select.js';
2
2
  import { isInteractive, printLine, processTerminal, } from '../auth-menu/terminal.js';
3
- import { hostEnrollmentPaths, vaultAuthority } from '../claustrum/enrollment.js';
3
+ import { hostEnrollmentPaths, readClaustrumEnrollmentStatus, validEnrollmentRequestedGrants, vaultAuthority, } from '../claustrum/enrollment.js';
4
4
  import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
5
5
  import { recordSetupEnrollment, setupEnrollmentLine } from './command-error.js';
6
6
  import { defaultCommandRunner } from './command-runner.js';
7
7
  import { detectHosts } from './detect.js';
8
8
  import { connectSetupHost, HostNotEnrolledError } from './enroll.js';
9
+ import { confirmEnrollmentAccess } from './enrollment-access.js';
9
10
  import { parseSetupFlags, UNAVAILABLE_HOST_MESSAGE } from './flags.js';
10
11
  import { setupPaths } from './paths.js';
11
12
  import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
@@ -22,6 +23,9 @@ function validatePlugin(plugin) {
22
23
  for (const host of Object.values(plugin.vault.hosts)) {
23
24
  if (!/^[a-z0-9][a-z0-9-]*$/.test(host.name))
24
25
  throw new Error('Setup requires lowercase vault names containing only letters, digits and dashes.');
26
+ if (host.requestedGrants !== undefined &&
27
+ !validEnrollmentRequestedGrants(host.requestedGrants))
28
+ throw new Error('invalid Claustrum enrollment requested grants');
25
29
  }
26
30
  }
27
31
  /**
@@ -31,10 +35,11 @@ function validatePlugin(plugin) {
31
35
  * authority once with `vaultAuthority`; if that read fails it stays
32
36
  * `unknown`.
33
37
  */
34
- async function enrollmentReport(plugin, hosts, recorded) {
38
+ async function enrollmentReport(plugin, hosts, recorded, recordedAccess) {
35
39
  const report = [];
36
40
  for (const host of hosts) {
37
41
  let outcome = recorded.get(host) ?? 'not-enrolled';
42
+ let access = recordedAccess.get(host);
38
43
  if (outcome === 'unknown') {
39
44
  const { name, paths } = plugin.vault.hosts[host];
40
45
  const authority = await vaultAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
@@ -42,8 +47,13 @@ async function enrollmentReport(plugin, hosts, recorded) {
42
47
  outcome = 'enrolled';
43
48
  else if (authority === 'local')
44
49
  outcome = 'not-enrolled';
50
+ if (outcome === 'enrolled') {
51
+ const status = await readClaustrumEnrollmentStatus(hostEnrollmentPaths(paths), name).catch(() => undefined);
52
+ if (status?.state === 'approved')
53
+ access = await confirmEnrollmentAccess({}, status, hostEnrollmentPaths(paths).tokenPath, plugin.vault.hosts[host].requestedGrants);
54
+ }
45
55
  }
46
- report.push({ host, outcome });
56
+ report.push({ host, outcome, ...(access && { access }) });
47
57
  }
48
58
  return report;
49
59
  }
@@ -207,6 +217,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
207
217
  // Each host's vault enrollment as it happens. A host the operator approved
208
218
  // stays enrolled if a later step fails, so a failure reports this record.
209
219
  const enrollment = new Map();
220
+ const enrollmentAccess = new Map();
210
221
  try {
211
222
  for (const host of hosts) {
212
223
  await stopped();
@@ -215,7 +226,9 @@ export async function runSetup(plugin, argv = [], io = {}) {
215
226
  if (useVault) {
216
227
  enrollment.set(host, 'unknown');
217
228
  try {
218
- await connectSetupHost(plugin, host, io, terminal, stopped);
229
+ const access = await connectSetupHost(plugin, host, io, terminal, stopped);
230
+ if (access)
231
+ enrollmentAccess.set(host, access);
219
232
  }
220
233
  catch (error) {
221
234
  if (error instanceof HostNotEnrolledError)
@@ -248,7 +261,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
248
261
  // then rethrow the original value untouched. Reporting must never
249
262
  // replace the failure, so its own errors are ignored.
250
263
  try {
251
- const report = await enrollmentReport(plugin, hosts, enrollment);
264
+ const report = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
252
265
  recordSetupEnrollment(error, report);
253
266
  for (const entry of report)
254
267
  printLine(terminal, setupEnrollmentLine(entry));
@@ -1,5 +1,5 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
- import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
2
+ import type { SetupEnrollmentAccess, SetupHost, SetupIO, SetupPlugin } from './types.js';
3
3
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
4
4
  export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read \"Upgrading from v0.1.3\" in its release notes first), or run setup without --claustrum to use local accounts.";
5
5
  /**
@@ -31,4 +31,4 @@ export declare class HostNotEnrolledError extends Error {
31
31
  });
32
32
  }
33
33
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
34
- export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<void>;
34
+ export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<SetupEnrollmentAccess | undefined>;
@@ -3,6 +3,7 @@ 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
5
  import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
6
+ import { confirmEnrollmentAccess, enrollmentAccessLines, } from './enrollment-access.js';
6
7
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
7
8
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
8
9
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
@@ -54,7 +55,7 @@ function approveCommand(requestId, name) {
54
55
  export async function connectSetupHost(plugin, host, io, terminal, fence) {
55
56
  if (hasVaultHost())
56
57
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
57
- const { name, displayName, paths: input } = plugin.vault.hosts[host];
58
+ const { name, displayName, requestedGrants, paths: input, } = plugin.vault.hosts[host];
58
59
  const paths = hostEnrollmentPaths(input);
59
60
  await fence();
60
61
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
@@ -69,6 +70,7 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
69
70
  const manager = new ClaustrumEnrollmentManager({
70
71
  proposedName: name,
71
72
  displayName,
73
+ requestedGrants,
72
74
  paths,
73
75
  // Each tick of the wait below checks the fence once, just before
74
76
  // reconcile proposes or polls. Checking again inside every vault call
@@ -85,7 +87,11 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
85
87
  const initial = await manager.status();
86
88
  if (initial.state === 'approved') {
87
89
  printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
88
- return;
90
+ const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
91
+ if (access)
92
+ for (const line of enrollmentAccessLines(access))
93
+ printLine(terminal, line);
94
+ return access;
89
95
  }
90
96
  printLine(terminal, `Asking the vault to connect ${name}…`);
91
97
  const deadline = now() + ENROLLMENT_WAIT_MS;
@@ -97,7 +103,11 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
97
103
  const status = await manager.reconcile();
98
104
  if (status.state === 'approved') {
99
105
  printLine(terminal, `Connected ${host} to Claustrum.`);
100
- return;
106
+ const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
107
+ if (access)
108
+ for (const line of enrollmentAccessLines(access))
109
+ printLine(terminal, line);
110
+ return access;
101
111
  }
102
112
  if (status.state === 'unavailable' &&
103
113
  status.code === UNSUPPORTED_ENROLLMENT_CODE)
@@ -0,0 +1,7 @@
1
+ import type { ClaustrumEnrollmentConnection, ClaustrumEnrollmentStatus, ClaustrumRequestedGrant } from '../claustrum/enrollment.js';
2
+ import type { SetupEnrollmentAccess } from './types.js';
3
+ /** Check access on the enrollment connection, after the token has reached disk. */
4
+ export declare function confirmEnrollmentAccess(client: Pick<ClaustrumEnrollmentConnection, 'listScoped'>, status: Extract<ClaustrumEnrollmentStatus, {
5
+ state: 'approved';
6
+ }>, tokenPath: string, configuredGrants: ReadonlyArray<ClaustrumRequestedGrant> | undefined): Promise<SetupEnrollmentAccess | undefined>;
7
+ export declare function enrollmentAccessLines(access: SetupEnrollmentAccess): string[];
@@ -0,0 +1,77 @@
1
+ import { readClaustrumEnrollmentToken } from '../claustrum/enrollment.js';
2
+ function shellArgument(value) {
3
+ if (/^[a-zA-Z0-9_:@./-]+$/.test(value))
4
+ return value;
5
+ return process.platform === 'win32'
6
+ ? `'${value.replaceAll("'", "''")}'`
7
+ : `'${value.replaceAll("'", "'\\''")}'`;
8
+ }
9
+ /** Check access on the enrollment connection, after the token has reached disk. */
10
+ export async function confirmEnrollmentAccess(client, status, tokenPath, configuredGrants) {
11
+ const requestedGrants = status.requestedGrants ?? configuredGrants;
12
+ if (!requestedGrants)
13
+ return undefined;
14
+ const grants = requestedGrants.map((grant) => ({
15
+ grant,
16
+ ...(status.approvedName !== undefined && {
17
+ grantCommand: `ck auth grant --principal ${shellArgument(`enrolled:${status.approvedName}`)} --selector-kind ${grant.selector.exact === undefined ? 'category' : 'exact'} --selector ${shellArgument(grant.selector.exact ?? grant.selector.category)} --operation ${grant.operation}`,
18
+ }),
19
+ }));
20
+ if (status.requestedGrantsStatus === 'dropped')
21
+ return { state: 'older-vault', grants };
22
+ try {
23
+ if (!client.listScoped)
24
+ return { state: 'unconfirmed', grants };
25
+ const { token } = await readClaustrumEnrollmentToken(tokenPath);
26
+ const inventory = await client.listScoped(token);
27
+ const confirmed = grants.map((entry) => ({
28
+ ...entry,
29
+ reachableLogins: inventory.rows.filter((row) => row.operations.includes(entry.grant.operation) &&
30
+ (entry.grant.selector.exact !== undefined
31
+ ? row.id === entry.grant.selector.exact
32
+ : row.categories.includes(entry.grant.selector.category))).length,
33
+ }));
34
+ return {
35
+ state: confirmed.every((entry) => entry.reachableLogins > 0)
36
+ ? 'reachable'
37
+ : confirmed.some((entry) => entry.reachableLogins > 0)
38
+ ? 'partial'
39
+ : 'no-logins',
40
+ grants: confirmed.map((entry) => {
41
+ if (entry.reachableLogins === 0)
42
+ return entry;
43
+ const { grantCommand: _, ...reachable } = entry;
44
+ return reachable;
45
+ }),
46
+ };
47
+ }
48
+ catch {
49
+ // A listing failure cannot undo approval, and its error may contain secrets.
50
+ return { state: 'unconfirmed', grants };
51
+ }
52
+ }
53
+ export function enrollmentAccessLines(access) {
54
+ const lines = [];
55
+ const remedy = access.grants.some((entry) => entry.grantCommand)
56
+ ? 'run:'
57
+ : 'check ck auth status for the approved name before granting access.';
58
+ if (access.state === 'older-vault')
59
+ lines.push(`Approved. This vault is too old to grant access with the approval; ${remedy}`);
60
+ else if (access.state === 'no-logins')
61
+ lines.push(`Approved, but no logins are reachable yet; ${remedy}`);
62
+ else if (access.state === 'partial')
63
+ lines.push(`Approved, but some requested access has no reachable logins yet; ${remedy}`);
64
+ else if (access.state === 'unconfirmed')
65
+ lines.push(`Approved, but access could not be confirmed; ${access.grants.some((entry) => entry.grantCommand) ? 'check ck auth status or run:' : remedy}`);
66
+ for (const { grant, reachableLogins, grantCommand } of access.grants) {
67
+ if (reachableLogins !== undefined && reachableLogins > 0) {
68
+ const target = grant.selector.exact === undefined
69
+ ? `the vault's ${JSON.stringify(grant.selector.category)} accounts`
70
+ : `credential ${JSON.stringify(grant.selector.exact)}`;
71
+ lines.push(`Confirmed ${grant.operation} access to ${target} (${reachableLogins} reachable ${reachableLogins === 1 ? 'login' : 'logins'}).`);
72
+ }
73
+ if (grantCommand)
74
+ lines.push(` ${grantCommand}`);
75
+ }
76
+ return lines;
77
+ }
@@ -5,4 +5,4 @@ export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, type HostNotEnrolledReason, U
5
5
  export { setupUsage } from './flags.js';
6
6
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
7
7
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
8
- export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
8
+ export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentAccess, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -1,5 +1,5 @@
1
1
  import type { MenuTerminal } from '../auth-menu/terminal.js';
2
- import type { ClaustrumEnrollmentConnection, hostEnrollmentPaths } from '../claustrum/index.js';
2
+ import type { ClaustrumEnrollmentConnection, ClaustrumRequestedGrant, hostEnrollmentPaths } from '../claustrum/index.js';
3
3
  export type SetupHost = 'opencode' | 'pi';
4
4
  export type OpenCodeGeneration = '1' | '2' | 'both';
5
5
  export type SetupEnvironment = Record<string, string | undefined>;
@@ -11,9 +11,19 @@ export type SetupEnvironment = Record<string, string | undefined>;
11
11
  * flight and the host's token file could not settle it.
12
12
  */
13
13
  export type SetupEnrollmentOutcome = 'enrolled' | 'not-enrolled' | 'unknown';
14
+ export interface SetupEnrollmentAccess {
15
+ state: 'reachable' | 'no-logins' | 'partial' | 'older-vault' | 'unconfirmed';
16
+ /** One result per requested grant, in proposal order. No count means unknown. */
17
+ grants: readonly {
18
+ grant: ClaustrumRequestedGrant;
19
+ reachableLogins?: number;
20
+ grantCommand?: string;
21
+ }[];
22
+ }
14
23
  export interface SetupHostEnrollment {
15
24
  host: SetupHost;
16
25
  outcome: SetupEnrollmentOutcome;
26
+ access?: SetupEnrollmentAccess;
17
27
  }
18
28
  /**
19
29
  * What setup decided before calling a plugin callback. The OpenCode generation
@@ -51,6 +61,7 @@ export interface SetupPlugin {
51
61
  hosts: Record<SetupHost, {
52
62
  name: string;
53
63
  displayName?: string;
64
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
54
65
  paths: Parameters<typeof hostEnrollmentPaths>[0];
55
66
  }>;
56
67
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.43.0",
3
+ "version": "0.44.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": {
@@ -169,7 +169,7 @@
169
169
  },
170
170
  "devDependencies": {
171
171
  "@biomejs/biome": "2.5.14",
172
- "@cortexkit/claustrum-client": "^0.16.0",
172
+ "@cortexkit/claustrum-client": "^0.18.0",
173
173
  "@cortexkit/opencode-sidebar": "0.1.0",
174
174
  "@cortexkit/subc-client": "0.24.0",
175
175
  "@earendil-works/pi-coding-agent": "1.0.4",