@cortexkit/common-auth 0.23.0 → 0.25.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.
- package/dist/claustrum/consumer.d.ts +7 -1
- package/dist/claustrum/consumer.js +17 -2
- package/dist/claustrum/enrollment.d.ts +5 -0
- package/dist/claustrum/enrollment.js +27 -0
- package/dist/claustrum/errors.d.ts +1 -1
- package/dist/claustrum/index.d.ts +1 -1
- package/dist/claustrum/index.js +1 -1
- package/dist/claustrum/roster.d.ts +31 -0
- package/dist/claustrum/roster.js +72 -0
- package/dist/commands/builtins.d.ts +37 -0
- package/dist/commands/builtins.js +95 -13
- package/dist/commands/index.d.ts +1 -1
- package/dist/fs/private-files.d.ts +2 -0
- package/dist/fs/private-files.js +49 -3
- package/dist/opencode2/install.d.ts +3 -2
- package/dist/opencode2/install.js +184 -63
- package/dist/opencode2/types.d.ts +43 -6
- package/dist/setup/enroll.d.ts +25 -4
- package/dist/setup/enroll.js +116 -34
- package/dist/setup/index.d.ts +1 -0
- package/dist/setup/index.js +1 -0
- package/dist/setup/process-fence.d.ts +7 -0
- package/dist/setup/process-fence.js +56 -1
- package/dist/setup/types.d.ts +5 -0
- package/package.json +2 -2
|
@@ -4,7 +4,7 @@ import type { RoutingRow } from '../routing/index.js';
|
|
|
4
4
|
import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser, type KeptReceiptState, type VaultGrantReach } from './custody.js';
|
|
5
5
|
import { type ClaustrumLogger } from './errors.js';
|
|
6
6
|
import { type InsulaQuotaOptions, type InsulaQuotaResult } from './insula.js';
|
|
7
|
-
import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
|
|
7
|
+
import { type AccountMapper, type QuotaReceipt, type ReorderVaultRosterResult, type VaultRosterFile } from './roster.js';
|
|
8
8
|
import { type WatchMode } from './watch.js';
|
|
9
9
|
export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
|
|
10
10
|
/**
|
|
@@ -157,6 +157,12 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
|
|
|
157
157
|
/** Decline a vault account: it stays listed and never routes until accepted. */
|
|
158
158
|
decline(routeId: string): Promise<void>;
|
|
159
159
|
accept(routeId: string): Promise<void>;
|
|
160
|
+
/**
|
|
161
|
+
* Set the order vault accounts are tried in (`reorderVaultRoster`), then
|
|
162
|
+
* re-read the roster, so the next routing decision in this process uses
|
|
163
|
+
* the new order without waiting for a discovery. Never contacts the vault.
|
|
164
|
+
*/
|
|
165
|
+
reorder(routeIds: readonly string[]): Promise<ReorderVaultRosterResult>;
|
|
160
166
|
/**
|
|
161
167
|
* Store a quota or profile observation for a vault route. The receipt the
|
|
162
168
|
* reading was taken with is required: the observation lands only while the
|
|
@@ -5,7 +5,7 @@ import { readClaustrumEnrollmentToken } from './enrollment.js';
|
|
|
5
5
|
import { ClaustrumConsumerError } from './errors.js';
|
|
6
6
|
import { acquireInsulaQuotaSource, } from './insula.js';
|
|
7
7
|
import { pendingVaultQuota, retainVaultQuotaWriter } from './quota-writer.js';
|
|
8
|
-
import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
|
|
8
|
+
import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, vaultRoutingRows, } from './roster.js';
|
|
9
9
|
import { SAFETY_POLL_MS } from './watch.js';
|
|
10
10
|
/**
|
|
11
11
|
* One plugin host's view of its vault accounts. It turns vault credentials
|
|
@@ -485,8 +485,12 @@ export class ClaustrumConsumer {
|
|
|
485
485
|
let current;
|
|
486
486
|
try {
|
|
487
487
|
current = await this.authorize(routeId, signal);
|
|
488
|
+
// Cancellation can land after authorize settles, before this continuation.
|
|
489
|
+
signal?.throwIfAborted();
|
|
488
490
|
}
|
|
489
|
-
catch {
|
|
491
|
+
catch (error) {
|
|
492
|
+
if (signal?.aborted)
|
|
493
|
+
throw error;
|
|
490
494
|
// Re-authorization failed: keep this 401 and report it against the
|
|
491
495
|
// receipt (served record version) this request was sent with.
|
|
492
496
|
}
|
|
@@ -522,6 +526,17 @@ export class ClaustrumConsumer {
|
|
|
522
526
|
await acceptVaultRoute(this.#options.rosterPath, routeId);
|
|
523
527
|
this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
|
|
524
528
|
}
|
|
529
|
+
/**
|
|
530
|
+
* Set the order vault accounts are tried in (`reorderVaultRoster`), then
|
|
531
|
+
* re-read the roster, so the next routing decision in this process uses
|
|
532
|
+
* the new order without waiting for a discovery. Never contacts the vault.
|
|
533
|
+
*/
|
|
534
|
+
async reorder(routeIds) {
|
|
535
|
+
this.#assertOpen();
|
|
536
|
+
const result = await reorderVaultRoster(this.#options.rosterPath, routeIds);
|
|
537
|
+
this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
|
|
538
|
+
return result;
|
|
539
|
+
}
|
|
525
540
|
/**
|
|
526
541
|
* Store a quota or profile observation for a vault route. The receipt the
|
|
527
542
|
* reading was taken with is required: the observation lands only while the
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { type ClaustrumClientOptions as ClaustrumEnrollmentClientOptions, type EnrollmentPollOutcome, type EnrollmentTokenFile, writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
|
|
2
|
+
/**
|
|
3
|
+
* The code a vault without the enrollment ceremony answers a proposal with.
|
|
4
|
+
* Setup reports it as "this vault cannot connect plugins" instead of waiting.
|
|
5
|
+
*/
|
|
6
|
+
export declare const UNSUPPORTED_ENROLLMENT_CODE = "unknown_method";
|
|
2
7
|
/**
|
|
3
8
|
* Codes the vault's closed enrollment-refusal vocabulary marks permanent. The
|
|
4
9
|
* client labels some module error frames transient/retry regardless, so the
|
|
@@ -10,12 +10,22 @@ const ENROLLMENT_SCHEMA = 1;
|
|
|
10
10
|
const ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
|
|
11
11
|
const ENROLLMENT_LOCK_TTL_MS = 30_000;
|
|
12
12
|
const TOKEN_RE = /^[0-9a-f]{64}$/;
|
|
13
|
+
/**
|
|
14
|
+
* The code a vault without the enrollment ceremony answers a proposal with.
|
|
15
|
+
* Setup reports it as "this vault cannot connect plugins" instead of waiting.
|
|
16
|
+
*/
|
|
17
|
+
export const UNSUPPORTED_ENROLLMENT_CODE = 'unknown_method';
|
|
13
18
|
/**
|
|
14
19
|
* Codes the vault's closed enrollment-refusal vocabulary marks permanent. The
|
|
15
20
|
* client labels some module error frames transient/retry regardless, so the
|
|
16
21
|
* producer's code takes precedence over the client's action for these.
|
|
17
22
|
*/
|
|
18
23
|
export const TERMINAL_ENROLLMENT_CODES = new Set([
|
|
24
|
+
// The daemon's answer to an operation it does not implement: a vault built
|
|
25
|
+
// before the enrollment ceremony. It arrives as a transport Error frame with
|
|
26
|
+
// no class, which claustrum-client before 0.13.0 labels transient/retry, but
|
|
27
|
+
// asking again can never succeed.
|
|
28
|
+
UNSUPPORTED_ENROLLMENT_CODE,
|
|
19
29
|
'invalid_params',
|
|
20
30
|
'pending_exists',
|
|
21
31
|
'not_found',
|
|
@@ -638,6 +648,23 @@ export class ClaustrumEnrollmentManager {
|
|
|
638
648
|
retryCode: refusal.code,
|
|
639
649
|
};
|
|
640
650
|
}
|
|
651
|
+
// A vault without the ceremony cannot hold a request for this
|
|
652
|
+
// proposal, now or from an earlier run (the state has no request
|
|
653
|
+
// id). So nothing is blocked and nothing is in progress: remove the
|
|
654
|
+
// pending state, still under the ceremony lock, so status reads as
|
|
655
|
+
// "not enrolled" and a reset or a later run starts afresh.
|
|
656
|
+
if (refusal.code === UNSUPPORTED_ENROLLMENT_CODE) {
|
|
657
|
+
await lock.assertOwned();
|
|
658
|
+
await unlink(this.#paths.statePath).catch((cause) => {
|
|
659
|
+
if (cause.code !== 'ENOENT')
|
|
660
|
+
throw cause;
|
|
661
|
+
});
|
|
662
|
+
return {
|
|
663
|
+
state: 'unavailable',
|
|
664
|
+
proposedName: state.proposedName,
|
|
665
|
+
code: refusal.code,
|
|
666
|
+
};
|
|
667
|
+
}
|
|
641
668
|
return this.#block(state, refusal.code);
|
|
642
669
|
}
|
|
643
670
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* `code`, a `class` and an `action`), so callers can tell the vault's verdict
|
|
5
5
|
* apart from a check made on this side.
|
|
6
6
|
*/
|
|
7
|
-
export type ClaustrumConsumerFailureKind = 'closed' | 'not-enrolled' | 'invalid-token' | 'unavailable' | 'identity-changed' | 'identity-unasserted' | 'insufficient-validity' | 'invalid-material' | 'not-active' | 'route-unavailable' | 'route-declined' | 'no-receipt' | 'unsafe-file' | 'invalid-state' | 'wrong-consumer' | 'roster-busy' | 'host-slot-login' | 'host-slot-placeholder' | 'placeholder-refresh';
|
|
7
|
+
export type ClaustrumConsumerFailureKind = 'closed' | 'not-enrolled' | 'invalid-token' | 'unavailable' | 'identity-changed' | 'identity-unasserted' | 'insufficient-validity' | 'invalid-material' | 'not-active' | 'route-unavailable' | 'route-declined' | 'no-receipt' | 'unsafe-file' | 'invalid-state' | 'wrong-consumer' | 'roster-busy' | 'host-slot-login' | 'host-slot-placeholder' | 'placeholder-refresh' | 'invalid-order';
|
|
8
8
|
export declare class ClaustrumConsumerError extends Error {
|
|
9
9
|
readonly kind: ClaustrumConsumerFailureKind;
|
|
10
10
|
constructor(kind: ClaustrumConsumerFailureKind, message: string);
|
|
@@ -10,7 +10,7 @@ export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHO
|
|
|
10
10
|
export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaLookup, type InsulaQuotaMiss, type InsulaQuotaOptions, type InsulaQuotaReading, type InsulaQuotaResult, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } from './insula.js';
|
|
11
11
|
export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
|
|
12
12
|
export { drainVaultQuota } from './quota-writer.js';
|
|
13
|
-
export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
|
|
13
|
+
export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, type ReorderVaultRosterOptions, type ReorderVaultRosterResult, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
|
|
14
14
|
export { type ChangeNotice, ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, type ScopedRosterWatchOptions, type ScopedWatchEnd, type ScopedWatchHandle, type ScopedWatchNoticeShape, type ScopedWatchSource, WATCH_RETRY_MS, type WatchMode, } from './watch.js';
|
|
15
15
|
/**
|
|
16
16
|
* Connect the client that lists and fetches this consumer's vault credentials
|
package/dist/claustrum/index.js
CHANGED
|
@@ -15,7 +15,7 @@ export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHO
|
|
|
15
15
|
export { acquireInsulaQuotaSource, } from './insula.js';
|
|
16
16
|
export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
|
|
17
17
|
export { drainVaultQuota } from './quota-writer.js';
|
|
18
|
-
export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
|
|
18
|
+
export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
|
|
19
19
|
export { ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, WATCH_RETRY_MS, } from './watch.js';
|
|
20
20
|
/**
|
|
21
21
|
* Connect the client that lists and fetches this consumer's vault credentials
|
|
@@ -119,6 +119,37 @@ export declare function mutateVaultRoster<T>(path: string, change: (current: Vau
|
|
|
119
119
|
export declare function declineVaultRoute(path: string, routeId: string): Promise<undefined>;
|
|
120
120
|
/** Lift the user's decline for a vault account and every alias of it. */
|
|
121
121
|
export declare function acceptVaultRoute(path: string, routeId: string): Promise<undefined>;
|
|
122
|
+
/** Options of `reorderVaultRoster`. */
|
|
123
|
+
export interface ReorderVaultRosterOptions {
|
|
124
|
+
/** Aborts the wait for the roster's write lock. */
|
|
125
|
+
signal?: AbortSignal;
|
|
126
|
+
}
|
|
127
|
+
export interface ReorderVaultRosterResult {
|
|
128
|
+
/** The route id order now on disk. */
|
|
129
|
+
ids: string[];
|
|
130
|
+
/** `unchanged` when the roster was already in this order; nothing was written. */
|
|
131
|
+
outcome: 'reordered' | 'unchanged';
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Set the order vault accounts are tried in. Routing reads that order from
|
|
135
|
+
* the roster's row order (`vaultRoutingRows`), and a later discovery keeps
|
|
136
|
+
* each account at its position, so the order lasts until the next reorder.
|
|
137
|
+
* The order is this host's routing preference: the vault has no order of its
|
|
138
|
+
* own, and this never contacts it.
|
|
139
|
+
*
|
|
140
|
+
* `routeIds` must name every roster route id exactly once; anything else
|
|
141
|
+
* (an unknown, missing or repeated id) refuses with `invalid-order` and
|
|
142
|
+
* writes nothing. It runs under the roster's write lock, like every other
|
|
143
|
+
* roster write, so a quota reading or decline committed meanwhile is kept.
|
|
144
|
+
* Each row is kept as the same object, so only the positions change: every
|
|
145
|
+
* row's fields and the rest of the file stay as they were. An order equal to
|
|
146
|
+
* the current one writes nothing. A host with no roster file yet has no
|
|
147
|
+
* routes, so only the empty order is accepted.
|
|
148
|
+
*
|
|
149
|
+
* A `ClaustrumConsumer` in the same process does not see the new order until
|
|
150
|
+
* it re-reads the file: call `consumer.reorder` instead to update both.
|
|
151
|
+
*/
|
|
152
|
+
export declare function reorderVaultRoster(path: string, routeIds: readonly string[], options?: ReorderVaultRosterOptions): Promise<ReorderVaultRosterResult>;
|
|
122
153
|
/**
|
|
123
154
|
* The receipt fields a quota or profile observation must carry to say which
|
|
124
155
|
* send (credential and account) it came from. Pass the
|
package/dist/claustrum/roster.js
CHANGED
|
@@ -378,6 +378,78 @@ export function acceptVaultRoute(path, routeId) {
|
|
|
378
378
|
};
|
|
379
379
|
});
|
|
380
380
|
}
|
|
381
|
+
function invalidOrder(message) {
|
|
382
|
+
return new ClaustrumConsumerError('invalid-order', message);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Why `routeIds` is not an order of these rows: it must name every distinct
|
|
386
|
+
* route id exactly once and nothing else. The message quotes only ids the
|
|
387
|
+
* caller supplied; route ids it left out are counted, not named.
|
|
388
|
+
*/
|
|
389
|
+
function vaultOrderProblem(rows, routeIds) {
|
|
390
|
+
if (!Array.isArray(routeIds))
|
|
391
|
+
return 'route ids must be an array of route ids';
|
|
392
|
+
const rosterIds = new Set(rows.map((row) => row.routeId));
|
|
393
|
+
const given = new Set();
|
|
394
|
+
for (const id of routeIds) {
|
|
395
|
+
if (typeof id !== 'string')
|
|
396
|
+
return 'route ids must be an array of route ids';
|
|
397
|
+
if (given.has(id))
|
|
398
|
+
return `route id ${id} appears more than once`;
|
|
399
|
+
if (!rosterIds.has(id))
|
|
400
|
+
return `route id ${id} is not in the roster`;
|
|
401
|
+
given.add(id);
|
|
402
|
+
}
|
|
403
|
+
const missing = [...rosterIds].filter((id) => !given.has(id)).length;
|
|
404
|
+
if (missing > 0)
|
|
405
|
+
return `the order leaves out ${missing} roster route id${missing === 1 ? '' : 's'}`;
|
|
406
|
+
return undefined;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Set the order vault accounts are tried in. Routing reads that order from
|
|
410
|
+
* the roster's row order (`vaultRoutingRows`), and a later discovery keeps
|
|
411
|
+
* each account at its position, so the order lasts until the next reorder.
|
|
412
|
+
* The order is this host's routing preference: the vault has no order of its
|
|
413
|
+
* own, and this never contacts it.
|
|
414
|
+
*
|
|
415
|
+
* `routeIds` must name every roster route id exactly once; anything else
|
|
416
|
+
* (an unknown, missing or repeated id) refuses with `invalid-order` and
|
|
417
|
+
* writes nothing. It runs under the roster's write lock, like every other
|
|
418
|
+
* roster write, so a quota reading or decline committed meanwhile is kept.
|
|
419
|
+
* Each row is kept as the same object, so only the positions change: every
|
|
420
|
+
* row's fields and the rest of the file stay as they were. An order equal to
|
|
421
|
+
* the current one writes nothing. A host with no roster file yet has no
|
|
422
|
+
* routes, so only the empty order is accepted.
|
|
423
|
+
*
|
|
424
|
+
* A `ClaustrumConsumer` in the same process does not see the new order until
|
|
425
|
+
* it re-reads the file: call `consumer.reorder` instead to update both.
|
|
426
|
+
*/
|
|
427
|
+
export function reorderVaultRoster(path, routeIds, options = {}) {
|
|
428
|
+
return mutateVaultRoster(path, (current) => {
|
|
429
|
+
const rows = current?.rows ?? [];
|
|
430
|
+
const problem = vaultOrderProblem(rows, routeIds);
|
|
431
|
+
if (problem)
|
|
432
|
+
throw invalidOrder(problem);
|
|
433
|
+
// Group by route id so a hand-edited file that repeats one keeps every
|
|
434
|
+
// copy: the later copies travel right after the first.
|
|
435
|
+
const byId = new Map();
|
|
436
|
+
for (const row of rows) {
|
|
437
|
+
const group = byId.get(row.routeId);
|
|
438
|
+
if (group)
|
|
439
|
+
group.push(row);
|
|
440
|
+
else
|
|
441
|
+
byId.set(row.routeId, [row]);
|
|
442
|
+
}
|
|
443
|
+
const ids = [...routeIds];
|
|
444
|
+
const next = ids.flatMap((id) => byId.get(id) ?? []);
|
|
445
|
+
if (!current || next.every((row, index) => row === rows[index]))
|
|
446
|
+
return { result: { ids, outcome: 'unchanged' } };
|
|
447
|
+
return {
|
|
448
|
+
next: { ...current, rows: next },
|
|
449
|
+
result: { ids, outcome: 'reordered' },
|
|
450
|
+
};
|
|
451
|
+
}, { ...(options.signal && { signal: options.signal }) });
|
|
452
|
+
}
|
|
381
453
|
/**
|
|
382
454
|
* What a receipt may do to a row's quota: `hold` (the row holds the receipt's
|
|
383
455
|
* credential and account), `bind` (the row has never had a known account and
|
|
@@ -48,6 +48,43 @@ export interface RoutingSectionOptions {
|
|
|
48
48
|
*/
|
|
49
49
|
orderedVariants?: MenuChoice[];
|
|
50
50
|
formerMainId?: string;
|
|
51
|
+
/**
|
|
52
|
+
* The vault accounts' routing order, for a plugin that can run in vault
|
|
53
|
+
* mode. Called on each build; return the order while the plugin routes
|
|
54
|
+
* through vault accounts and undefined otherwise. While it returns one, the
|
|
55
|
+
* section shows and sets the vault accounts' order (by the name the menu
|
|
56
|
+
* shows for each account) instead of the pool roster's. Wire it to
|
|
57
|
+
* `ClaustrumConsumer.snapshot()` and `ClaustrumConsumer.reorder`, or to
|
|
58
|
+
* `readVaultRoster` and `reorderVaultRoster` for a plugin without a
|
|
59
|
+
* consumer.
|
|
60
|
+
*/
|
|
61
|
+
vaultOrder?: () => VaultRoutingOrder | undefined | Promise<VaultRoutingOrder | undefined>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The order vault accounts are tried in, as the Routing section reads and
|
|
65
|
+
* sets it in vault mode. Shaped after `/claustrum`'s roster, without
|
|
66
|
+
* importing it, so the menu does not need the vault client.
|
|
67
|
+
*/
|
|
68
|
+
export interface VaultRoutingOrder {
|
|
69
|
+
/**
|
|
70
|
+
* Every vault roster row, in roster (routing) order: its route id and the
|
|
71
|
+
* name the plugin shows for that account (the roster row's `label`, or its
|
|
72
|
+
* email). Route ids are long and opaque, so the section shows and accepts
|
|
73
|
+
* labels; a route id is still accepted wherever a label is.
|
|
74
|
+
*/
|
|
75
|
+
rows: readonly {
|
|
76
|
+
id: string;
|
|
77
|
+
label: string;
|
|
78
|
+
}[];
|
|
79
|
+
/**
|
|
80
|
+
* Sets the order. `ids` are route ids, every one exactly once. Wire it to
|
|
81
|
+
* `ClaustrumConsumer.reorder` or `reorderVaultRoster`, which refuse any
|
|
82
|
+
* other list without writing.
|
|
83
|
+
*/
|
|
84
|
+
reorder(ids: readonly string[]): Promise<{
|
|
85
|
+
ids: readonly string[];
|
|
86
|
+
outcome: 'reordered' | 'unchanged';
|
|
87
|
+
}>;
|
|
51
88
|
}
|
|
52
89
|
export interface LimitsSectionOptions {
|
|
53
90
|
/**
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// the same locks as any other writer of those files.
|
|
5
5
|
import { formatQuota, isQuotaMap, projectQuota, quotaWindowName, } from '../quota/index.js';
|
|
6
6
|
import { DEFAULT_FORMER_MAIN_ID, orderForPlacement, resolveRoutingMode, } from '../routing/index.js';
|
|
7
|
-
import { projectFailure, } from './seam.js';
|
|
7
|
+
import { CommandError, projectFailure, } from './seam.js';
|
|
8
8
|
/** `disabledReason` recorded when the user disables an account from the menu. */
|
|
9
9
|
export const MENU_DISABLED_REASON = 'disabled from the command menu';
|
|
10
10
|
function isRecord(value) {
|
|
@@ -65,13 +65,16 @@ function addedText(name, result) {
|
|
|
65
65
|
function failureMessage(error) {
|
|
66
66
|
return projectFailure(error).text;
|
|
67
67
|
}
|
|
68
|
-
async function snapshot(
|
|
68
|
+
async function snapshot(options) {
|
|
69
|
+
const { store } = options;
|
|
69
70
|
const load = await store.read();
|
|
70
71
|
const read = await store.readSettings();
|
|
72
|
+
const vault = await options.routing?.vaultOrder?.();
|
|
71
73
|
return {
|
|
72
74
|
load,
|
|
73
75
|
rows: distinctRows(load),
|
|
74
76
|
settings: read.status === 'error' ? {} : read.settings,
|
|
77
|
+
...(vault ? { vault } : {}),
|
|
75
78
|
};
|
|
76
79
|
}
|
|
77
80
|
function accountView(row, options) {
|
|
@@ -323,6 +326,73 @@ function quotaSection(options, snap) {
|
|
|
323
326
|
},
|
|
324
327
|
};
|
|
325
328
|
}
|
|
329
|
+
/**
|
|
330
|
+
* Sets the vault order. The roster's own refusal of the list (`invalid-order`:
|
|
331
|
+
* an account left out, which it counts without naming) is shown with its own
|
|
332
|
+
* message; any other failure is projected as usual. The kind is read from
|
|
333
|
+
* the error object so the menu does not import the vault client.
|
|
334
|
+
*/
|
|
335
|
+
async function reorderVault(vault, order) {
|
|
336
|
+
try {
|
|
337
|
+
return await vault.reorder(order);
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
if (error instanceof Error &&
|
|
341
|
+
error.name === 'ClaustrumConsumerError' &&
|
|
342
|
+
error.kind === 'invalid-order')
|
|
343
|
+
throw new CommandError('vault-invalid-order', error.message, {
|
|
344
|
+
cause: error,
|
|
345
|
+
});
|
|
346
|
+
throw error;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function invalidVaultOrder(message) {
|
|
350
|
+
return new CommandError('vault-invalid-order', message);
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* How the Routing section names vault accounts: by label, since route ids
|
|
354
|
+
* are long and opaque. A typed entry may be a label or a route id, and must
|
|
355
|
+
* name exactly one account. Refusals quote only the entry the user typed.
|
|
356
|
+
*/
|
|
357
|
+
function vaultNames(vault) {
|
|
358
|
+
const rows = vault.rows.map((row) => ({
|
|
359
|
+
id: row.id,
|
|
360
|
+
label: row.label.trim() || row.id,
|
|
361
|
+
}));
|
|
362
|
+
const matches = (entry) => rows.filter((row) => row.id === entry || row.label === entry);
|
|
363
|
+
return {
|
|
364
|
+
ids: rows.map((row) => row.id),
|
|
365
|
+
nameOf: (id) => rows.find((row) => row.id === id)?.label ?? id,
|
|
366
|
+
/**
|
|
367
|
+
* What the order input starts with for an account: its label when
|
|
368
|
+
* typing that label back names this account alone, else its route id
|
|
369
|
+
* (two accounts sharing a label, or a label with a comma or line break
|
|
370
|
+
* in it, either of which would split it into two entries).
|
|
371
|
+
*/
|
|
372
|
+
entryOf: (id) => {
|
|
373
|
+
const row = rows.find((entry) => entry.id === id);
|
|
374
|
+
return row && !/[,\n]/.test(row.label) && matches(row.label).length === 1
|
|
375
|
+
? row.label
|
|
376
|
+
: id;
|
|
377
|
+
},
|
|
378
|
+
/** The route ids the typed entries name, in order; refuses before any write. */
|
|
379
|
+
resolve: (entries) => {
|
|
380
|
+
const ids = [];
|
|
381
|
+
for (const entry of entries) {
|
|
382
|
+
const found = matches(entry);
|
|
383
|
+
if (found.length === 0)
|
|
384
|
+
throw invalidVaultOrder(`"${entry}" is not a vault account.`);
|
|
385
|
+
if (found.length > 1)
|
|
386
|
+
throw invalidVaultOrder(`"${entry}" matches more than one vault account; enter those accounts by route id.`);
|
|
387
|
+
const id = found[0].id;
|
|
388
|
+
if (ids.includes(id))
|
|
389
|
+
throw invalidVaultOrder(`"${entry}" names an account already in the order.`);
|
|
390
|
+
ids.push(id);
|
|
391
|
+
}
|
|
392
|
+
return ids;
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
}
|
|
326
396
|
function routingSection(options, snap) {
|
|
327
397
|
const { store, extraLocks } = options;
|
|
328
398
|
const locks = extraLocks ? { extraLocks } : {};
|
|
@@ -336,14 +406,18 @@ function routingSection(options, snap) {
|
|
|
336
406
|
? raw
|
|
337
407
|
: 'ordered';
|
|
338
408
|
const resolved = resolveRoutingMode(current);
|
|
339
|
-
|
|
409
|
+
// In vault mode routing tries the vault accounts, so their order is the
|
|
410
|
+
// one shown and set here; the pool roster's order is not used.
|
|
411
|
+
const vault = snap.vault ? vaultNames(snap.vault) : undefined;
|
|
412
|
+
const ids = vault ? vault.ids : snap.rows.map((row) => row.id);
|
|
413
|
+
const nameOf = (id) => (vault ? vault.nameOf(id) : id);
|
|
340
414
|
const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
|
|
341
415
|
const label = choices.find((choice) => choice.value === current)?.label ?? current;
|
|
342
416
|
const lines = [`Mode: ${label}`];
|
|
343
417
|
if (ids.length > 0)
|
|
344
|
-
lines.push(
|
|
418
|
+
lines.push(`${vault ? 'Vault account order' : 'Roster order'}: ${ids.map(nameOf).join(', ')}`);
|
|
345
419
|
if (resolved.mode === 'ordered' && tried.join() !== ids.join())
|
|
346
|
-
lines.push(`Tried in order: ${tried.join(', ')}`);
|
|
420
|
+
lines.push(`Tried in order: ${tried.map(nameOf).join(', ')}`);
|
|
347
421
|
const actions = [
|
|
348
422
|
{
|
|
349
423
|
id: 'mode',
|
|
@@ -371,19 +445,27 @@ function routingSection(options, snap) {
|
|
|
371
445
|
{
|
|
372
446
|
kind: 'text',
|
|
373
447
|
id: 'order',
|
|
374
|
-
label:
|
|
375
|
-
|
|
448
|
+
label: vault
|
|
449
|
+
? 'Vault accounts, first to last, separated by commas'
|
|
450
|
+
: 'Account ids, first to last',
|
|
451
|
+
value: vault ? ids.map(vault.entryOf).join(', ') : ids.join(', '),
|
|
376
452
|
required: true,
|
|
377
453
|
},
|
|
378
454
|
],
|
|
379
455
|
run: async ({ values }) => {
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
const
|
|
456
|
+
const text = String(values.order);
|
|
457
|
+
// A vault label may contain spaces, so vault entries are separated by
|
|
458
|
+
// commas or line breaks, not spaces; pool ids never contain spaces.
|
|
459
|
+
const entries = text
|
|
460
|
+
.split(vault ? /[,\n]+/ : /[\s,]+/)
|
|
461
|
+
.map((entry) => entry.trim())
|
|
462
|
+
.filter((entry) => entry.length > 0);
|
|
463
|
+
const result = snap.vault && vault
|
|
464
|
+
? await reorderVault(snap.vault, vault.resolve(entries))
|
|
465
|
+
: await store.reorder(entries, locks);
|
|
384
466
|
return result.outcome === 'unchanged'
|
|
385
467
|
? 'The order is unchanged.'
|
|
386
|
-
: `Order set to ${result.ids.join(', ')}.`;
|
|
468
|
+
: `Order set to ${result.ids.map(nameOf).join(', ')}.`;
|
|
387
469
|
},
|
|
388
470
|
});
|
|
389
471
|
return {
|
|
@@ -524,7 +606,7 @@ function limitsSection(options, snap) {
|
|
|
524
606
|
}
|
|
525
607
|
/** The four built-in sections, in their fixed order, from one read of the store. */
|
|
526
608
|
export async function builtinSections(options) {
|
|
527
|
-
const snap = await snapshot(options
|
|
609
|
+
const snap = await snapshot(options);
|
|
528
610
|
return [
|
|
529
611
|
accountsSection(options, snap),
|
|
530
612
|
quotaSection(options, snap),
|
package/dist/commands/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { AccountsSectionOptions, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, } from './builtins.js';
|
|
1
|
+
export type { AccountsSectionOptions, 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';
|
|
@@ -5,6 +5,8 @@ type Backend = typeof import('@cortexkit/private-files');
|
|
|
5
5
|
type Kind = 'file' | 'directory';
|
|
6
6
|
/** Tests inject a backend here; production always imports the private-files package. */
|
|
7
7
|
export declare function setPrivateFilesBackendForTest(api?: Backend): void;
|
|
8
|
+
/** The fixed `reason` of a refusal because the Windows native addon did not load. */
|
|
9
|
+
export declare const PRIVATE_FILES_UNAVAILABLE_REASON = "native-addon-unavailable";
|
|
8
10
|
export declare class PrivateFileError extends Error {
|
|
9
11
|
readonly path: string;
|
|
10
12
|
readonly stage: string;
|
package/dist/fs/private-files.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { lstat, readFile, rename, unlink } from 'node:fs/promises';
|
|
3
|
-
import {
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
5
|
export const windowsPrivateFiles = process.platform === 'win32';
|
|
5
6
|
const migrationNotices = new Set();
|
|
6
7
|
function ioCode(detail) {
|
|
@@ -20,8 +21,51 @@ let backend;
|
|
|
20
21
|
export function setPrivateFilesBackendForTest(api) {
|
|
21
22
|
backend = api ? Promise.resolve(api) : undefined;
|
|
22
23
|
}
|
|
24
|
+
/** The fixed `reason` of a refusal because the Windows native addon did not load. */
|
|
25
|
+
export const PRIVATE_FILES_UNAVAILABLE_REASON = 'native-addon-unavailable';
|
|
26
|
+
function privateFilesUnavailable(cause) {
|
|
27
|
+
return Object.assign(new Error('Windows private-files native addon is unavailable', { cause }), {
|
|
28
|
+
code: 'ERR_PRIVATE_FILES_UNAVAILABLE',
|
|
29
|
+
reason: PRIVATE_FILES_UNAVAILABLE_REASON,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function isUnavailable(api, error) {
|
|
33
|
+
return (error instanceof api.PrivateFilesUnavailableError ||
|
|
34
|
+
error?.code ===
|
|
35
|
+
'ERR_PRIVATE_FILES_UNAVAILABLE');
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Importing @cortexkit/private-files succeeds even when its Windows addon
|
|
39
|
+
* cannot load: the package loads the addon on first use, and some of its
|
|
40
|
+
* checks then report the failure as an ordinary refusal such as
|
|
41
|
+
* `unsupported-filesystem`. So prove the addon loads before handing the
|
|
42
|
+
* package out. Verifying a path that does not exist loads the addon first and
|
|
43
|
+
* then fails harmlessly; only the package's own "unavailable" error means the
|
|
44
|
+
* addon is missing.
|
|
45
|
+
*/
|
|
46
|
+
async function assertNativeAddonLoads(api) {
|
|
47
|
+
try {
|
|
48
|
+
await api.verifyPrivatePath(join(tmpdir(), `.common-auth-private-files-probe-${randomUUID()}`), 'file');
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (isUnavailable(api, error))
|
|
52
|
+
throw privateFilesUnavailable(error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Load the package once per process. On Windows a failed import or addon load
|
|
57
|
+
* is kept, so every later private-file operation refuses at once with
|
|
58
|
+
* ERR_PRIVATE_FILES_UNAVAILABLE. There is no fallback to permission bits:
|
|
59
|
+
* they do not protect files on Windows.
|
|
60
|
+
*/
|
|
23
61
|
function loadBackend() {
|
|
24
|
-
backend ??= import('@cortexkit/private-files')
|
|
62
|
+
backend ??= import('@cortexkit/private-files').then(async (api) => {
|
|
63
|
+
if (windowsPrivateFiles)
|
|
64
|
+
await assertNativeAddonLoads(api);
|
|
65
|
+
return api;
|
|
66
|
+
}, (cause) => {
|
|
67
|
+
throw windowsPrivateFiles ? privateFilesUnavailable(cause) : cause;
|
|
68
|
+
});
|
|
25
69
|
return backend;
|
|
26
70
|
}
|
|
27
71
|
export class PrivateFileError extends Error {
|
|
@@ -38,7 +82,9 @@ export class PrivateFileError extends Error {
|
|
|
38
82
|
orphanPath;
|
|
39
83
|
constructor(path, stage, cause) {
|
|
40
84
|
const detail = cause;
|
|
41
|
-
super(
|
|
85
|
+
super(detail?.code === 'ERR_PRIVATE_FILES_UNAVAILABLE'
|
|
86
|
+
? `Private file refused at ${stage}: ${path} (${PRIVATE_FILES_UNAVAILABLE_REASON}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
|
|
87
|
+
: `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
|
|
42
88
|
this.path = path;
|
|
43
89
|
this.stage = stage;
|
|
44
90
|
this.name = 'PrivateFileError';
|
|
@@ -26,8 +26,9 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
|
|
|
26
26
|
* whether output has started and when the response ended, attributed to
|
|
27
27
|
* an attempt by the rules below;
|
|
28
28
|
* - `retry` asks the host to retry at once when an account was refused
|
|
29
|
-
* before any output
|
|
30
|
-
*
|
|
29
|
+
* before any output and `chooseAccount` names another account for the
|
|
30
|
+
* next attempt, keeps the host's decision when the refused account was the
|
|
31
|
+
* last one that can serve, and refuses to retry once output has started.
|
|
31
32
|
*
|
|
32
33
|
* Attribution. A send belongs to the attempt named by the mark
|
|
33
34
|
* `model.request` left on it, so several attempts of one session and kind
|