@cortexkit/common-auth 0.43.0 → 0.45.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.
Files changed (59) hide show
  1. package/dist/claustrum/enrollment.d.ts +25 -4
  2. package/dist/claustrum/enrollment.js +81 -4
  3. package/dist/claustrum/index.d.ts +1 -1
  4. package/dist/claustrum/index.js +1 -1
  5. package/dist/commands/builtins.d.ts +20 -1
  6. package/dist/commands/builtins.js +28 -12
  7. package/dist/commands/index.d.ts +1 -1
  8. package/dist/commands/menu.d.ts +6 -1
  9. package/dist/commands/menu.js +1 -0
  10. package/dist/fs/file-read-cache.d.ts +3 -0
  11. package/dist/fs/file-read-cache.js +9 -5
  12. package/dist/fs/refresh-file-lock.d.ts +11 -0
  13. package/dist/fs/refresh-file-lock.js +146 -2
  14. package/dist/fs/with-lock.d.ts +2 -0
  15. package/dist/fs/with-lock.js +1 -1
  16. package/dist/settings/define.d.ts +35 -0
  17. package/dist/settings/define.js +52 -0
  18. package/dist/settings/descriptors.d.ts +97 -0
  19. package/dist/settings/descriptors.js +81 -0
  20. package/dist/settings/edit.d.ts +24 -0
  21. package/dist/settings/edit.js +229 -0
  22. package/dist/settings/fs.d.ts +6 -0
  23. package/dist/settings/fs.js +19 -0
  24. package/dist/settings/handle.d.ts +30 -0
  25. package/dist/settings/handle.js +228 -0
  26. package/dist/settings/index.d.ts +10 -0
  27. package/dist/settings/index.js +7 -0
  28. package/dist/settings/lock-errors.d.ts +2 -0
  29. package/dist/settings/lock-errors.js +15 -0
  30. package/dist/settings/move.d.ts +76 -0
  31. package/dist/settings/move.js +351 -0
  32. package/dist/settings/parse.d.ts +24 -0
  33. package/dist/settings/parse.js +65 -0
  34. package/dist/settings/paths.d.ts +12 -0
  35. package/dist/settings/paths.js +48 -0
  36. package/dist/settings/refusal.d.ts +7 -0
  37. package/dist/settings/refusal.js +15 -0
  38. package/dist/settings/resolve.d.ts +15 -0
  39. package/dist/settings/resolve.js +51 -0
  40. package/dist/settings/schema.d.ts +29 -0
  41. package/dist/settings/schema.js +81 -0
  42. package/dist/settings/snapshot.d.ts +24 -0
  43. package/dist/settings/snapshot.js +150 -0
  44. package/dist/settings/update.d.ts +6 -0
  45. package/dist/settings/update.js +139 -0
  46. package/dist/settings/write.d.ts +26 -0
  47. package/dist/settings/write.js +88 -0
  48. package/dist/setup/command-error.d.ts +1 -1
  49. package/dist/setup/command-error.js +4 -2
  50. package/dist/setup/command.js +23 -6
  51. package/dist/setup/enroll.d.ts +2 -2
  52. package/dist/setup/enroll.js +13 -3
  53. package/dist/setup/enrollment-access.d.ts +7 -0
  54. package/dist/setup/enrollment-access.js +86 -0
  55. package/dist/setup/index.d.ts +1 -1
  56. package/dist/setup/types.d.ts +16 -1
  57. package/dist/tui-prefs/watcher.d.ts +3 -1
  58. package/dist/tui-prefs/watcher.js +41 -18
  59. package/package.json +6 -2
@@ -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';
@@ -1,4 +1,4 @@
1
- import type { AddInput, PoolLockSpec, PoolRow, PoolStore, RemoveOptions } from '../store/index.js';
1
+ import type { AddInput, PoolLockSpec, PoolRow, PoolSettings, PoolStore, RemoveOptions, SettingsMutator } from '../store/index.js';
2
2
  import type { CommandInvocation, KnobValues, MenuChoice, MenuKnob } from './model.js';
3
3
  import { type ResolvedSection } from './seam.js';
4
4
  /**
@@ -98,9 +98,28 @@ export interface LimitsSectionOptions {
98
98
  */
99
99
  labels?: readonly string[];
100
100
  }
101
+ /**
102
+ * Where the Routing and Limits sections read and write the settings they show
103
+ * (`routing.mode`, `routing.maxSameAccountWait`, `killswitch.enabled`,
104
+ * `killswitch.accounts`). Without a port they use the account store's own
105
+ * settings through `readSettings` and `updateSettings`. A plugin that moved
106
+ * its settings to its own file (`./settings`) passes a port that translates
107
+ * this store-shaped view to that file.
108
+ */
109
+ export interface BuiltinSettingsPort {
110
+ /** The current settings, in the store's settings shape. */
111
+ read(): Promise<PoolSettings>;
112
+ /**
113
+ * Apply one menu change. `mutator` gets a private copy in the store's shape
114
+ * and edits it in place or returns the whole next object, as with
115
+ * `updateSettings`. A refusal is thrown and shown as the action's failure.
116
+ */
117
+ update(mutator: SettingsMutator): Promise<void>;
118
+ }
101
119
  export interface BuiltinOptions {
102
120
  store: PoolStore;
103
121
  extraLocks?: readonly PoolLockSpec[];
122
+ settings?: BuiltinSettingsPort;
104
123
  now: () => number;
105
124
  accounts?: AccountsSectionOptions;
106
125
  quota?: QuotaSectionOptions;
@@ -65,15 +65,31 @@ function addedText(name, result) {
65
65
  function failureMessage(error) {
66
66
  return projectFailure(error).text;
67
67
  }
68
+ /** The plugin's settings port, or one over the account store's own settings. */
69
+ function settingsPort(options) {
70
+ if (options.settings)
71
+ return options.settings;
72
+ const { store, extraLocks } = options;
73
+ const locks = extraLocks ? { extraLocks } : {};
74
+ return {
75
+ async read() {
76
+ const read = await store.readSettings();
77
+ return read.status === 'error' ? {} : read.settings;
78
+ },
79
+ async update(mutator) {
80
+ await store.updateSettings(mutator, locks);
81
+ },
82
+ };
83
+ }
68
84
  async function snapshot(options) {
69
85
  const { store } = options;
70
86
  const load = await store.read();
71
- const read = await store.readSettings();
87
+ const settings = await settingsPort(options).read();
72
88
  const vault = await options.routing?.vaultOrder?.();
73
89
  return {
74
90
  load,
75
91
  rows: distinctRows(load),
76
- settings: read.status === 'error' ? {} : read.settings,
92
+ settings,
77
93
  ...(vault ? { vault } : {}),
78
94
  };
79
95
  }
@@ -396,6 +412,7 @@ function vaultNames(vault) {
396
412
  function routingSection(options, snap) {
397
413
  const { store, extraLocks } = options;
398
414
  const locks = extraLocks ? { extraLocks } : {};
415
+ const port = settingsPort(options);
399
416
  const choices = [
400
417
  { value: 'ordered', label: 'Ordered (roster order)' },
401
418
  ...(options.routing?.orderedVariants ?? []),
@@ -428,10 +445,10 @@ function routingSection(options, snap) {
428
445
  ],
429
446
  run: async ({ values }) => {
430
447
  const mode = String(values.mode);
431
- await store.updateSettings((settings) => {
448
+ await port.update((settings) => {
432
449
  settings.routing = { ...record(settings.routing), mode };
433
450
  return undefined;
434
- }, locks);
451
+ });
435
452
  return `Routing mode set to ${choices.find((choice) => choice.value === mode)?.label ?? mode}.`;
436
453
  },
437
454
  },
@@ -495,13 +512,13 @@ function routingSection(options, snap) {
495
512
  run: async ({ values }) => {
496
513
  const value = String(values.maxSameAccountWait);
497
514
  const maxSameAccountWait = value === 'max' ? 'max' : Number(value);
498
- await store.updateSettings((settings) => {
515
+ await port.update((settings) => {
499
516
  settings.routing = {
500
517
  ...record(settings.routing),
501
518
  maxSameAccountWait,
502
519
  };
503
520
  return undefined;
504
- }, locks);
521
+ });
505
522
  return `${waitLabel} set to ${waitName(value)}.`;
506
523
  },
507
524
  });
@@ -541,8 +558,7 @@ function floorNames(options, snap) {
541
558
  return (label) => names.get(label) ?? label;
542
559
  }
543
560
  function limitsSection(options, snap) {
544
- const { store, extraLocks } = options;
545
- const locks = extraLocks ? { extraLocks } : {};
561
+ const port = settingsPort(options);
546
562
  const killswitch = record(snap.settings.killswitch);
547
563
  const enabled = killswitch.enabled === true;
548
564
  const floors = record(killswitch.accounts);
@@ -577,7 +593,7 @@ function limitsSection(options, snap) {
577
593
  : {}),
578
594
  })),
579
595
  run: async ({ values }) => {
580
- await store.updateSettings((settings) => {
596
+ await port.update((settings) => {
581
597
  const next = record(settings.killswitch);
582
598
  const accounts = record(next.accounts);
583
599
  const mine = record(accounts[row.id]);
@@ -598,7 +614,7 @@ function limitsSection(options, snap) {
598
614
  delete next.accounts;
599
615
  settings.killswitch = next;
600
616
  return undefined;
601
- }, locks);
617
+ });
602
618
  return `Floors updated for ${name}.`;
603
619
  },
604
620
  },
@@ -628,13 +644,13 @@ function limitsSection(options, snap) {
628
644
  ],
629
645
  run: async ({ values }) => {
630
646
  const on = values.enabled === true;
631
- await store.updateSettings((settings) => {
647
+ await port.update((settings) => {
632
648
  settings.killswitch = {
633
649
  ...record(settings.killswitch),
634
650
  enabled: on,
635
651
  };
636
652
  return undefined;
637
- }, locks);
653
+ });
638
654
  return `Killswitch ${on ? 'on' : 'off'}.`;
639
655
  },
640
656
  },
@@ -1,4 +1,4 @@
1
- export type { AccountsSectionOptions, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, VaultRoutingOrder, } from './builtins.js';
1
+ export type { AccountsSectionOptions, BuiltinSettingsPort, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, VaultRoutingOrder, } from './builtins.js';
2
2
  export { MENU_DISABLED_REASON } from './builtins.js';
3
3
  export type { CommandMenu, CommandMenuOptions, StoreSectionSlot, } from './menu.js';
4
4
  export { createCommandMenu, parseApplyRequest } from './menu.js';
@@ -1,6 +1,6 @@
1
1
  import { type RedactionOptions } from '../logger/index.js';
2
2
  import type { PoolLockSpec, PoolStore } from '../store/index.js';
3
- import { type AccountsSectionOptions, type LimitsSectionOptions, type QuotaSectionOptions, type RoutingSectionOptions } from './builtins.js';
3
+ import { type AccountsSectionOptions, type BuiltinSettingsPort, type LimitsSectionOptions, type QuotaSectionOptions, type RoutingSectionOptions } from './builtins.js';
4
4
  import type { CommandApplyRequest, CommandApplyResult, CommandDialogPayload, CommandInvocation, PluginExtraSection, PluginSection } from './model.js';
5
5
  import { type SeamLogger } from './seam.js';
6
6
  /** The four slots the library can build from a pool store. */
@@ -25,6 +25,11 @@ export interface CommandMenuOptions {
25
25
  replace?: Partial<Record<StoreSectionSlot, PluginSection>>;
26
26
  /** The plugin's legacy locks, passed to every store write the menu makes. */
27
27
  extraLocks?: readonly PoolLockSpec[];
28
+ /**
29
+ * Where the Routing and Limits sections read and write their settings. Omit
30
+ * it to use the store's own settings, as before.
31
+ */
32
+ settings?: BuiltinSettingsPort;
28
33
  accounts?: AccountsSectionOptions;
29
34
  quota?: QuotaSectionOptions;
30
35
  routing?: RoutingSectionOptions;
@@ -156,6 +156,7 @@ export function createCommandMenu(options) {
156
156
  store,
157
157
  now,
158
158
  ...(options.extraLocks ? { extraLocks: options.extraLocks } : {}),
159
+ ...(options.settings ? { settings: options.settings } : {}),
159
160
  ...(options.accounts ? { accounts: options.accounts } : {}),
160
161
  ...(options.quota ? { quota: options.quota } : {}),
161
162
  ...(options.routing ? { routing: options.routing } : {}),
@@ -1,10 +1,13 @@
1
1
  import type { Stats } from 'node:fs';
2
2
  type FileIdentity = Stats | 'absent';
3
+ type Probe = (path: string) => Promise<Stats>;
3
4
  /** Process-local reads, capped at 64 path sets with one value per resolved set. */
4
5
  export declare class FileReadCache<T> {
5
6
  #private;
6
7
  constructor(options?: {
7
8
  followSymlinks?: boolean;
9
+ stat?: Probe;
10
+ lstat?: Probe;
8
11
  });
9
12
  read(paths: readonly string[], read: (resolvedPaths: string[]) => Promise<T>, validateHit?: (identities: readonly FileIdentity[]) => void): Promise<T>;
10
13
  }
@@ -1,10 +1,10 @@
1
1
  import { lstat, stat } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
- async function identity(path, followSymlinks) {
3
+ async function identity(path, probe) {
4
4
  try {
5
5
  // Match the reader: private readers reject links, while readFile follows
6
6
  // them and needs the target's identity, not the link's identity.
7
- const metadata = await (followSymlinks ? stat(path) : lstat(path));
7
+ const metadata = await probe(path);
8
8
  return metadata.isFile() ? metadata : undefined;
9
9
  }
10
10
  catch (error) {
@@ -24,15 +24,19 @@ function sameIdentity(left, right) {
24
24
  }
25
25
  /** Process-local reads, capped at 64 path sets with one value per resolved set. */
26
26
  export class FileReadCache {
27
- #followSymlinks;
27
+ #probe;
28
28
  #entries = new Map();
29
29
  constructor(options = {}) {
30
- this.#followSymlinks = options.followSymlinks ?? false;
30
+ // Look the probe up on every call, not once here: tests replace the
31
+ // node:fs/promises functions (and SettingsFs methods) after caches exist.
32
+ this.#probe = options.followSymlinks
33
+ ? (path) => (options.stat ?? stat)(path)
34
+ : (path) => (options.lstat ?? lstat)(path);
31
35
  }
32
36
  async read(paths, read, validateHit) {
33
37
  const resolvedPaths = paths.map((path) => resolve(path));
34
38
  const key = JSON.stringify(resolvedPaths);
35
- const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
39
+ const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#probe)));
36
40
  const identities = probed.every((entry) => entry !== undefined)
37
41
  ? probed
38
42
  : undefined;
@@ -4,6 +4,17 @@ type LeaseCreationTestHooks = {
4
4
  };
5
5
  /** Test-only creation faults; not re-exported from the public fs entry point. */
6
6
  export declare function setLeaseCreationTestHooksForTest(hooks?: LeaseCreationTestHooks): void;
7
+ type StagingSweepTestHooks = {
8
+ readdir?: (directory: string) => Promise<string[]>;
9
+ beforeUnlink?: (path: string) => void | Promise<void>;
10
+ unlink?: (path: string) => Promise<void>;
11
+ };
12
+ /** Test-only sweep faults; not re-exported from the public fs entry point. */
13
+ export declare function setStagingSweepTestHooksForTest(hooks?: StagingSweepTestHooks): void;
14
+ /** Tests only: wait for every staging sweep started so far to finish. */
15
+ export declare function settleStagingSweepsForTest(): Promise<void>;
16
+ /** Tests only: let the next acquisition of every lock path sweep again. */
17
+ export declare function forgetStagingSweepsForTest(): void;
7
18
  export declare function isLostMarkerRaceError(error: unknown): boolean;
8
19
  /** Test-only fault injection between marker mkdir and owner.json write. */
9
20
  export interface EvictionMarkerTestHooks {