@cortexkit/common-auth 0.42.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.
@@ -193,6 +193,7 @@ export interface CacheKeepStatus {
193
193
  */
194
194
  export declare class CacheKeepManager<M = undefined> {
195
195
  private readonly targets;
196
+ private readonly lastDropReasons;
196
197
  private readonly adapter;
197
198
  private readonly now;
198
199
  private readonly log;
@@ -228,6 +229,17 @@ export declare class CacheKeepManager<M = undefined> {
228
229
  start(): void;
229
230
  /** Disarm, abort any warm in flight and forget every target. */
230
231
  stop(): void;
232
+ /**
233
+ * Read whether a session is armed, without I/O or callbacks. Stop reasons
234
+ * include manager-internal values: plugins must filter them through
235
+ * isCacheWarmStopReason for billing, leaving unknown reasons out, not guessing.
236
+ */
237
+ warming(sessionKey: string): {
238
+ on: true;
239
+ } | {
240
+ on: false;
241
+ stopReason?: string;
242
+ };
231
243
  /** A snapshot without captured bodies, which can hold prompt content. */
232
244
  status(): CacheKeepStatus;
233
245
  /**
@@ -42,6 +42,7 @@ function positive(value, fallback) {
42
42
  */
43
43
  export class CacheKeepManager {
44
44
  targets = new Map();
45
+ lastDropReasons = new Map();
45
46
  adapter;
46
47
  now;
47
48
  log;
@@ -170,6 +171,7 @@ export class CacheKeepManager {
170
171
  warmCount: 0,
171
172
  };
172
173
  this.targets.set(sessionKey, target);
174
+ this.lastDropReasons.delete(sessionKey);
173
175
  this.totalBytes += bodyBytes;
174
176
  this.log?.debug('cachekeep captured target', { sessionKey, accountId });
175
177
  this.start();
@@ -217,6 +219,22 @@ export class CacheKeepManager {
217
219
  this.totalBytes = 0;
218
220
  this.log?.debug('cachekeep stopped');
219
221
  }
222
+ /**
223
+ * Read whether a session is armed, without I/O or callbacks. Stop reasons
224
+ * include manager-internal values: plugins must filter them through
225
+ * isCacheWarmStopReason for billing, leaving unknown reasons out, not guessing.
226
+ */
227
+ warming(sessionKey) {
228
+ try {
229
+ if (this.targets.has(sessionKey))
230
+ return { on: true };
231
+ const stopReason = this.lastDropReasons.get(sessionKey);
232
+ return { on: false, ...(stopReason !== undefined ? { stopReason } : {}) };
233
+ }
234
+ catch {
235
+ return { on: false };
236
+ }
237
+ }
220
238
  /** A snapshot without captured bodies, which can hold prompt content. */
221
239
  status() {
222
240
  const window = this.getWindow?.();
@@ -687,6 +705,16 @@ export class CacheKeepManager {
687
705
  this.clearPlanTimer(target);
688
706
  this.totalBytes -= target.bodyBytes;
689
707
  this.targets.delete(sessionKey);
708
+ if (reason !== null) {
709
+ this.lastDropReasons.delete(sessionKey);
710
+ this.lastDropReasons.set(sessionKey, reason);
711
+ while (this.lastDropReasons.size > this.maxTargets * 4) {
712
+ const oldest = this.lastDropReasons.keys().next();
713
+ if (oldest.done)
714
+ break;
715
+ this.lastDropReasons.delete(oldest.value);
716
+ }
717
+ }
690
718
  if (reason !== null && target.hasWarmed && this.adapter.onWarmStopped) {
691
719
  this.report(() => this.adapter.onWarmStopped?.(sessionKey, { at: this.now(), reason }));
692
720
  }
@@ -85,6 +85,12 @@ export declare const VAULT_FAILURE_CLASSES: Readonly<{
85
85
  * kind stays `unavailable` for callers handling ClaustrumConsumerError.
86
86
  */
87
87
  export declare class ClaustrumUnreachableError extends ClaustrumConsumerError {
88
- constructor();
88
+ /**
89
+ * Non-secret host connection diagnostic. A missing accessor can recover
90
+ * once the host bridge installs; a failed accessor could not provide a client.
91
+ * Other unreachable failures leave this unset. Never use adapter error text.
92
+ */
93
+ readonly reason?: 'host-accessor-missing' | 'host-accessor-failed';
94
+ constructor(reason?: ClaustrumUnreachableError['reason']);
89
95
  }
90
96
  export declare function classifyVaultFailure(error: unknown): VaultFailureClass;
@@ -87,9 +87,17 @@ export const VAULT_FAILURE_CLASSES = Object.freeze({
87
87
  * kind stays `unavailable` for callers handling ClaustrumConsumerError.
88
88
  */
89
89
  export class ClaustrumUnreachableError extends ClaustrumConsumerError {
90
- constructor() {
90
+ /**
91
+ * Non-secret host connection diagnostic. A missing accessor can recover
92
+ * once the host bridge installs; a failed accessor could not provide a client.
93
+ * Other unreachable failures leave this unset. Never use adapter error text.
94
+ */
95
+ reason;
96
+ constructor(reason) {
91
97
  super('unavailable', 'Claustrum scoped operation unavailable');
92
98
  this.name = 'ClaustrumUnreachableError';
99
+ if (reason === 'host-accessor-missing' || reason === 'host-accessor-failed')
100
+ this.reason = reason;
93
101
  }
94
102
  }
95
103
  export function classifyVaultFailure(error) {
@@ -279,6 +279,15 @@ export declare class ClaustrumScopedCustody {
279
279
  setTimeoutImpl?: typeof setTimeout;
280
280
  clearTimeoutImpl?: typeof clearTimeout;
281
281
  });
282
+ /**
283
+ * Replace the connection to the same vault without discarding receipts or
284
+ * their enrollment tokens. Open roster watches restart on the new client;
285
+ * their existing handles remain usable. Passing the current client does nothing.
286
+ * Neither client is closed here: the caller closes the old one, and custody's
287
+ * close()/dispose() still closes the client it holds at shutdown.
288
+ * While hosted, next must come from connectVaultHost, as in the constructor.
289
+ */
290
+ replaceClient(next: ClaustrumScopedClient): void;
282
291
  /** A watch losing its transport is the same outage as an unreachable read. */
283
292
  transportLost(error?: unknown): void;
284
293
  /** Any vault answer ends transport fallback, even when it refuses access. */
@@ -312,8 +321,8 @@ export declare class ClaustrumScopedCustody {
312
321
  * Report that a send this consumer actually made was rejected. Only a 401
313
322
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
314
323
  * credential id with the exact record version that send was served, and
315
- * sent through the client and enrollment token that authorized it. A receipt
316
- * this custody did not issue is refused rather than reported.
324
+ * sent through the current client with the enrollment token that authorized
325
+ * it. A receipt this custody did not issue is refused rather than reported.
317
326
  */
318
327
  reportFailure(attempt: ClaustrumScopedAttempt, status: number, reporterSource: ClaustrumReporterSource): Promise<void>;
319
328
  /**
@@ -238,8 +238,15 @@ export class ClaustrumScopedCustody {
238
238
  this.#warnShutdown = shutdownWarning(this.#logger);
239
239
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
240
240
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
241
+ const currentClient = () => this.#client;
241
242
  this.#usage = new ScopedUsageReporter({
242
- client: this.#client,
243
+ client: {
244
+ // Queued readings follow a replacement without losing client capability checks.
245
+ get reportUsageScoped() {
246
+ const client = currentClient();
247
+ return client.reportUsageScoped?.bind(client);
248
+ },
249
+ },
243
250
  owns: (id) => this.#usageServed.has(id),
244
251
  token: async () => hasVaultHost() ? '' : checkedEnrollmentToken(await this.#readToken()),
245
252
  logger: this.#logger,
@@ -247,6 +254,24 @@ export class ClaustrumScopedCustody {
247
254
  clearTimeout: this.#clearTimeout,
248
255
  });
249
256
  }
257
+ /**
258
+ * Replace the connection to the same vault without discarding receipts or
259
+ * their enrollment tokens. Open roster watches restart on the new client;
260
+ * their existing handles remain usable. Passing the current client does nothing.
261
+ * Neither client is closed here: the caller closes the old one, and custody's
262
+ * close()/dispose() still closes the client it holds at shutdown.
263
+ * While hosted, next must come from connectVaultHost, as in the constructor.
264
+ */
265
+ replaceClient(next) {
266
+ this.#check();
267
+ if (next === this.#client)
268
+ return;
269
+ if (hasVaultHost() && !isVaultHostClient(next))
270
+ throw new ClaustrumUnreachableError();
271
+ this.#client = next;
272
+ for (const watch of this.#watches)
273
+ watch.restart();
274
+ }
250
275
  /** A watch losing its transport is the same outage as an unreachable read. */
251
276
  transportLost(error) {
252
277
  if (this.#closed || this.#outage)
@@ -255,7 +280,9 @@ export class ClaustrumScopedCustody {
255
280
  this.#outageError =
256
281
  error instanceof ClaustrumCredentialError
257
282
  ? error
258
- : new ClaustrumUnreachableError();
283
+ : new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError
284
+ ? error.reason
285
+ : undefined);
259
286
  this.#logger.warn('serving kept vault receipt', { reason: 'unreachable' });
260
287
  this.#scheduleProbe();
261
288
  }
@@ -367,7 +394,7 @@ export class ClaustrumScopedCustody {
367
394
  if (error instanceof ClaustrumCredentialError)
368
395
  throw error;
369
396
  if (classifyVaultFailure(error) === 'unreachable')
370
- throw new ClaustrumUnreachableError();
397
+ throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
371
398
  throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation unavailable');
372
399
  }
373
400
  finally {
@@ -603,7 +630,7 @@ export class ClaustrumScopedCustody {
603
630
  if (kept.since === null)
604
631
  kept.since = this.#now();
605
632
  const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
606
- this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token, client: this.#client });
633
+ this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token });
607
634
  this.#keptAttempts.set(attempt, routeId);
608
635
  return attempt;
609
636
  }
@@ -684,15 +711,15 @@ export class ClaustrumScopedCustody {
684
711
  recordVersion: served.recordVersion,
685
712
  expiresAtMs,
686
713
  }, 'accessToken', { value: accessToken, enumerable: false }));
687
- this.#provenance.set(attempt, { token, client: this.#client });
714
+ this.#provenance.set(attempt, { token });
688
715
  return attempt;
689
716
  }
690
717
  /**
691
718
  * Report that a send this consumer actually made was rejected. Only a 401
692
719
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
693
720
  * credential id with the exact record version that send was served, and
694
- * sent through the client and enrollment token that authorized it. A receipt
695
- * this custody did not issue is refused rather than reported.
721
+ * sent through the current client with the enrollment token that authorized
722
+ * it. A receipt this custody did not issue is refused rather than reported.
696
723
  */
697
724
  async reportFailure(attempt, status, reporterSource) {
698
725
  if (status !== 401)
@@ -719,7 +746,7 @@ export class ClaustrumScopedCustody {
719
746
  const pending = this.#reports.get(attempt);
720
747
  if (pending)
721
748
  return pending;
722
- const report = this.#call(() => provenance.client.reportAuthFailureScoped({
749
+ const report = this.#call(() => this.#client.reportAuthFailureScoped({
723
750
  credentialId: attempt.credentialId,
724
751
  enrollmentToken: provenance.token,
725
752
  providerStatus: 401,
@@ -761,36 +788,67 @@ export class ClaustrumScopedCustody {
761
788
  */
762
789
  watchRoster(options) {
763
790
  this.#check();
764
- const watch = new ScopedRosterWatch({
765
- client: this.#client,
766
- enrollmentToken: () => this.#token(),
767
- view: options.view ?? (() => this.#discoveredView),
768
- discover: async (view) => {
769
- await options.onView(view);
770
- },
771
- onRefused: (error) => {
772
- // Apply a refused watch as discover() applies a refused account
773
- // listing: every kept receipt is dropped.
774
- this.listFailed(error);
775
- options.onRefused?.(error);
791
+ const currentView = options.view ?? (() => this.#discoveredView);
792
+ let discovering;
793
+ let watch;
794
+ const create = (resubscribed = false) => {
795
+ const opened = new ScopedRosterWatch({
796
+ client: this.#client,
797
+ enrollmentToken: () => this.#token(),
798
+ // Nothing observed the gap between clients, even if the view is unchanged.
799
+ view: () => (resubscribed ? undefined : currentView()),
800
+ discover: async (view) => {
801
+ // An old watch's discovery may still be committing the host's roster.
802
+ while (discovering)
803
+ await discovering.catch(() => { });
804
+ if (watch !== opened)
805
+ return;
806
+ resubscribed = false;
807
+ discovering = Promise.resolve().then(() => options.onView(view));
808
+ try {
809
+ await discovering;
810
+ }
811
+ finally {
812
+ discovering = undefined;
813
+ }
814
+ },
815
+ onRefused: (error) => {
816
+ // Apply a refused watch as discover() applies a refused account
817
+ // listing: every kept receipt is dropped.
818
+ this.listFailed(error);
819
+ options.onRefused?.(error);
820
+ },
821
+ onTransportLost: () => this.transportLost(),
822
+ onReachable: () => this.reachable(),
823
+ onError: options.onError,
824
+ onMode: options.onMode,
825
+ logger: this.#logger,
826
+ now: this.#now,
827
+ setTimeoutImpl: this.#setTimeout,
828
+ clearTimeoutImpl: this.#clearTimeout,
829
+ });
830
+ return opened;
831
+ };
832
+ watch = create();
833
+ const tracked = {
834
+ restart: () => {
835
+ const previousMode = watch.mode;
836
+ watch.stop();
837
+ watch = create(true);
838
+ if (previousMode !== watch.mode)
839
+ options.onMode?.(watch.mode);
840
+ watch.start();
776
841
  },
777
- onTransportLost: () => this.transportLost(),
778
- onReachable: () => this.reachable(),
779
- onError: options.onError,
780
- onMode: options.onMode,
781
- logger: this.#logger,
782
- now: this.#now,
783
- setTimeoutImpl: this.#setTimeout,
784
- clearTimeoutImpl: this.#clearTimeout,
785
- });
786
- this.#watches.add(watch);
842
+ stop: () => watch.stop(),
843
+ };
844
+ this.#watches.add(tracked);
787
845
  watch.start();
788
846
  return {
789
847
  get mode() {
790
848
  return watch.mode;
791
849
  },
792
850
  close: () => {
793
- this.#watches.delete(watch);
851
+ this.#watches.delete(tracked);
794
852
  watch.stop();
795
853
  },
796
854
  };
@@ -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.
@@ -29,10 +29,31 @@ export declare function classifyEnrollmentError(error: unknown): {
29
29
  * Each host enrolls separately so the operator can revoke one without the other.
30
30
  */
31
31
  export declare function enrollmentName(plugin: string, host: string): string;
32
+ /** Match the vault's plain-text, code-point limit before proposing a display name. */
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
+ }
32
51
  export interface ClaustrumEnrollmentClient {
33
52
  enrollPropose(input: {
34
53
  name: string;
35
54
  requestSecretHash: string;
55
+ displayName?: string;
56
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
36
57
  }): Promise<{
37
58
  requestId: string;
38
59
  }>;
@@ -43,6 +64,7 @@ export interface ClaustrumEnrollmentClient {
43
64
  }
44
65
  export interface ClaustrumEnrollmentConnection extends ClaustrumEnrollmentClient {
45
66
  close(): void;
67
+ listScoped?: ClaustrumWireClient['listScoped'];
46
68
  }
47
69
  /**
48
70
  * Connect the enrollment ceremony. Setup calls this; the request path never
@@ -54,17 +76,17 @@ export declare function connectClaustrumEnrollmentClient(options: ClaustrumEnrol
54
76
  }): Promise<ClaustrumEnrollmentConnection>;
55
77
  export type ClaustrumEnrollmentStatus = {
56
78
  state: 'idle';
57
- } | {
79
+ } | (EnrollmentGrantProposal & {
58
80
  state: 'pending';
59
81
  proposedName: string;
60
82
  requestId?: string;
61
83
  retryCode?: string;
62
- } | {
84
+ }) | (EnrollmentGrantProposal & {
63
85
  state: 'approved';
64
86
  proposedName: string;
65
87
  approvedName?: string;
66
88
  tokenGeneration: number;
67
- } | {
89
+ }) | {
68
90
  state: 'denied';
69
91
  proposedName: string;
70
92
  } | {
@@ -142,6 +164,8 @@ export declare class ClaustrumEnrollmentManager {
142
164
  client: ClaustrumEnrollmentClient;
143
165
  paths: ClaustrumEnrollmentPaths;
144
166
  proposedName: string;
167
+ displayName?: string;
168
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
145
169
  now?: () => number;
146
170
  mintSecret?: () => string;
147
171
  writeTokenFile?: typeof writeEnrollmentTokenFile;
@@ -178,3 +202,4 @@ export type ClaustrumEnrollmentDisconnectResult = 'disconnected' | 'idle' | 'bus
178
202
  * wrong owner, not owner-only) refuses with `unsafe-file` and both files stay.
179
203
  */
180
204
  export declare function disconnectClaustrumEnrollment(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentDisconnectResult>;
205
+ export {};
@@ -68,6 +68,42 @@ export function enrollmentName(plugin, host) {
68
68
  throw new ClaustrumConsumerError('invalid-state', 'Claustrum enrollment names use lowercase letters, digits and dashes');
69
69
  return `${plugin}-${host}`;
70
70
  }
71
+ /** Match the vault's plain-text, code-point limit before proposing a display name. */
72
+ export function validEnrollmentDisplayName(displayName) {
73
+ const length = Array.from(displayName).length;
74
+ return (length >= 1 &&
75
+ length <= 40 &&
76
+ !/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test(displayName));
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
+ }
71
107
  /**
72
108
  * Connect the enrollment ceremony. Setup calls this; the request path never
73
109
  * does. `connectionFile` is required because this library reads no
@@ -122,6 +158,7 @@ function decodeEnrollmentState(value) {
122
158
  throw invalidState();
123
159
  }
124
160
  if (value.phase === 'pending') {
161
+ const grants = decodeGrantProposal(value);
125
162
  if (!TOKEN_RE.test(String(value.requestSecret ?? '')) ||
126
163
  (value.requestId !== undefined &&
127
164
  (typeof value.requestId !== 'string' ||
@@ -140,9 +177,11 @@ function decodeEnrollmentState(value) {
140
177
  }),
141
178
  createdAt: value.createdAt,
142
179
  updatedAt: value.updatedAt,
180
+ ...grants,
143
181
  };
144
182
  }
145
183
  if (value.phase === 'approved') {
184
+ const grants = decodeGrantProposal(value);
146
185
  if ((value.approvedName !== undefined &&
147
186
  (typeof value.approvedName !== 'string' ||
148
187
  value.approvedName.length === 0)) ||
@@ -159,6 +198,7 @@ function decodeEnrollmentState(value) {
159
198
  }),
160
199
  tokenGeneration: value.tokenGeneration,
161
200
  updatedAt: value.updatedAt,
201
+ ...grants,
162
202
  };
163
203
  }
164
204
  if (value.phase === 'denied' || value.phase === 'blocked') {
@@ -178,6 +218,18 @@ function decodeEnrollmentState(value) {
178
218
  }
179
219
  throw invalidState();
180
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
+ }
181
233
  function decodeTokenFile(value) {
182
234
  if (!isRecord(value) ||
183
235
  !TOKEN_RE.test(String(value.token ?? '')) ||
@@ -445,6 +497,9 @@ async function readEnrollmentStatus(paths, proposedName) {
445
497
  approvedName: state.approvedName,
446
498
  }),
447
499
  tokenGeneration: token.token_generation,
500
+ ...(state &&
501
+ (state.phase === 'approved' || state.phase === 'pending') &&
502
+ grantProposal(state)),
448
503
  },
449
504
  };
450
505
  }
@@ -527,6 +582,7 @@ function statusFromState(state) {
527
582
  state: 'pending',
528
583
  proposedName: state.proposedName,
529
584
  ...(state.requestId !== undefined && { requestId: state.requestId }),
585
+ ...grantProposal(state),
530
586
  };
531
587
  }
532
588
  if (state.phase === 'approved') {
@@ -537,6 +593,7 @@ function statusFromState(state) {
537
593
  approvedName: state.approvedName,
538
594
  }),
539
595
  tokenGeneration: state.tokenGeneration,
596
+ ...grantProposal(state),
540
597
  };
541
598
  }
542
599
  if (state.phase === 'denied')
@@ -559,15 +616,28 @@ export class ClaustrumEnrollmentManager {
559
616
  #client;
560
617
  #paths;
561
618
  #proposedName;
619
+ #displayName;
620
+ #requestedGrants;
562
621
  #now;
563
622
  #mintSecret;
564
623
  #writeTokenFile;
565
624
  #ancestorOptions;
566
625
  constructor(options) {
626
+ if (options.displayName !== undefined &&
627
+ !validEnrollmentDisplayName(options.displayName))
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
+ }));
567
636
  this.#ancestorOptions = options.ancestorOptions ?? {};
568
637
  this.#client = options.client;
569
638
  this.#paths = options.paths;
570
639
  this.#proposedName = options.proposedName;
640
+ this.#displayName = options.displayName;
571
641
  this.#now = options.now ?? Date.now;
572
642
  this.#mintSecret =
573
643
  options.mintSecret ?? (() => randomBytes(32).toString('hex'));
@@ -615,6 +685,7 @@ export class ClaustrumEnrollmentManager {
615
685
  phase: 'approved',
616
686
  proposedName: state?.proposedName ?? this.#proposedName,
617
687
  tokenGeneration: token.token_generation,
688
+ ...(state && grantProposal(state)),
618
689
  updatedAt: this.#now(),
619
690
  };
620
691
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -628,6 +699,7 @@ export class ClaustrumEnrollmentManager {
628
699
  approvedName: state.approvedName,
629
700
  }),
630
701
  tokenGeneration: token.token_generation,
702
+ ...(state.phase === 'approved' && grantProposal(state)),
631
703
  };
632
704
  }
633
705
  if (state?.phase === 'approved') {
@@ -652,6 +724,9 @@ export class ClaustrumEnrollmentManager {
652
724
  requestSecret: this.#mintSecret(),
653
725
  createdAt: now,
654
726
  updatedAt: now,
727
+ ...(this.#requestedGrants !== undefined && {
728
+ requestedGrants: this.#requestedGrants,
729
+ }),
655
730
  };
656
731
  if (!TOKEN_RE.test(state.requestSecret))
657
732
  throw new ClaustrumConsumerError('invalid-state', 'invalid minted Claustrum enrollment secret');
@@ -665,14 +740,44 @@ export class ClaustrumEnrollmentManager {
665
740
  const requestSecretHash = createHash('sha256')
666
741
  .update(Buffer.from(state.requestSecret, 'hex'))
667
742
  .digest('hex');
668
- const proposed = await this.#client.enrollPropose({
743
+ const proposal = {
669
744
  name: state.proposedName,
670
745
  requestSecretHash,
671
- });
746
+ };
747
+ let proposed;
748
+ let requestedGrantsStatus = state.requestedGrantsStatus;
749
+ try {
750
+ proposed = await this.#client.enrollPropose({
751
+ ...proposal,
752
+ ...(this.#displayName !== undefined && {
753
+ displayName: this.#displayName,
754
+ }),
755
+ ...(state.requestedGrants !== undefined && {
756
+ requestedGrants: state.requestedGrants,
757
+ }),
758
+ });
759
+ if (state.requestedGrants !== undefined)
760
+ requestedGrantsStatus = 'sent';
761
+ }
762
+ catch (error) {
763
+ if ((this.#displayName === undefined &&
764
+ state.requestedGrants === undefined) ||
765
+ !(error instanceof ClaustrumCredentialError) ||
766
+ error.code !== 'invalid_params')
767
+ throw error;
768
+ // Both optional fields were validated locally. Older vaults reject
769
+ // either field without storing a proposal, so retry the plain shape once.
770
+ proposed = await this.#client.enrollPropose(proposal);
771
+ if (state.requestedGrants !== undefined)
772
+ requestedGrantsStatus = 'dropped';
773
+ }
672
774
  state = {
673
775
  ...state,
674
776
  requestId: proposed.requestId,
675
777
  updatedAt: this.#now(),
778
+ ...(requestedGrantsStatus !== undefined && {
779
+ requestedGrantsStatus,
780
+ }),
676
781
  };
677
782
  await writeStateAtomic(this.#paths.statePath, state, this.#ancestorOptions);
678
783
  }
@@ -685,6 +790,7 @@ export class ClaustrumEnrollmentManager {
685
790
  state: 'pending',
686
791
  proposedName: state.proposedName,
687
792
  retryCode: refusal.code,
793
+ ...grantProposal(state),
688
794
  };
689
795
  }
690
796
  // A vault without the ceremony cannot hold a request for this
@@ -741,6 +847,7 @@ export class ClaustrumEnrollmentManager {
741
847
  proposedName: state.proposedName,
742
848
  approvedName: outcome.name,
743
849
  tokenGeneration: outcome.tokenGeneration,
850
+ ...grantProposal(state),
744
851
  updatedAt: this.#now(),
745
852
  };
746
853
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -756,6 +863,7 @@ export class ClaustrumEnrollmentManager {
756
863
  proposedName: state.proposedName,
757
864
  requestId,
758
865
  retryCode: refusal.code,
866
+ ...grantProposal(state),
759
867
  };
760
868
  }
761
869
  return this.#block(state, refusal.code);