@cortexkit/common-auth 0.44.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.
- package/dist/commands/builtins.d.ts +20 -1
- package/dist/commands/builtins.js +28 -12
- package/dist/commands/index.d.ts +1 -1
- package/dist/commands/menu.d.ts +6 -1
- package/dist/commands/menu.js +1 -0
- package/dist/fs/file-read-cache.d.ts +3 -0
- package/dist/fs/file-read-cache.js +9 -5
- package/dist/fs/refresh-file-lock.d.ts +11 -0
- package/dist/fs/refresh-file-lock.js +146 -2
- package/dist/fs/with-lock.d.ts +2 -0
- package/dist/fs/with-lock.js +1 -1
- package/dist/settings/define.d.ts +35 -0
- package/dist/settings/define.js +52 -0
- package/dist/settings/descriptors.d.ts +97 -0
- package/dist/settings/descriptors.js +81 -0
- package/dist/settings/edit.d.ts +24 -0
- package/dist/settings/edit.js +229 -0
- package/dist/settings/fs.d.ts +6 -0
- package/dist/settings/fs.js +19 -0
- package/dist/settings/handle.d.ts +30 -0
- package/dist/settings/handle.js +228 -0
- package/dist/settings/index.d.ts +10 -0
- package/dist/settings/index.js +7 -0
- package/dist/settings/lock-errors.d.ts +2 -0
- package/dist/settings/lock-errors.js +15 -0
- package/dist/settings/move.d.ts +76 -0
- package/dist/settings/move.js +351 -0
- package/dist/settings/parse.d.ts +24 -0
- package/dist/settings/parse.js +65 -0
- package/dist/settings/paths.d.ts +12 -0
- package/dist/settings/paths.js +48 -0
- package/dist/settings/refusal.d.ts +7 -0
- package/dist/settings/refusal.js +15 -0
- package/dist/settings/resolve.d.ts +15 -0
- package/dist/settings/resolve.js +51 -0
- package/dist/settings/schema.d.ts +29 -0
- package/dist/settings/schema.js +81 -0
- package/dist/settings/snapshot.d.ts +24 -0
- package/dist/settings/snapshot.js +150 -0
- package/dist/settings/update.d.ts +6 -0
- package/dist/settings/update.js +139 -0
- package/dist/settings/write.d.ts +26 -0
- package/dist/settings/write.js +88 -0
- package/dist/setup/command-error.d.ts +1 -1
- package/dist/setup/command-error.js +3 -2
- package/dist/setup/command.js +5 -1
- package/dist/setup/enroll.js +3 -3
- package/dist/setup/enrollment-access.d.ts +1 -1
- package/dist/setup/enrollment-access.js +13 -4
- package/dist/setup/types.d.ts +4 -0
- package/dist/tui-prefs/watcher.d.ts +3 -1
- package/dist/tui-prefs/watcher.js +41 -18
- package/package.json +5 -1
|
@@ -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
|
|
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
|
|
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
|
|
448
|
+
await port.update((settings) => {
|
|
432
449
|
settings.routing = { ...record(settings.routing), mode };
|
|
433
450
|
return undefined;
|
|
434
|
-
}
|
|
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
|
|
515
|
+
await port.update((settings) => {
|
|
499
516
|
settings.routing = {
|
|
500
517
|
...record(settings.routing),
|
|
501
518
|
maxSameAccountWait,
|
|
502
519
|
};
|
|
503
520
|
return undefined;
|
|
504
|
-
}
|
|
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
|
|
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
|
|
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
|
-
}
|
|
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
|
|
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
|
-
}
|
|
653
|
+
});
|
|
638
654
|
return `Killswitch ${on ? 'on' : 'off'}.`;
|
|
639
655
|
},
|
|
640
656
|
},
|
package/dist/commands/index.d.ts
CHANGED
|
@@ -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';
|
package/dist/commands/menu.d.ts
CHANGED
|
@@ -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;
|
package/dist/commands/menu.js
CHANGED
|
@@ -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,
|
|
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 (
|
|
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
|
-
#
|
|
27
|
+
#probe;
|
|
28
28
|
#entries = new Map();
|
|
29
29
|
constructor(options = {}) {
|
|
30
|
-
|
|
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.#
|
|
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 {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { link, lstat, mkdir, open, readFile, rename, rm, stat, } from 'node:fs/promises';
|
|
3
|
-
import { dirname, join } from 'node:path';
|
|
2
|
+
import { link, lstat, mkdir, open, readdir, readFile, rename, rm, stat, unlink, } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
4
|
import { DisappearedLockRecordError, isWindowsAccessDeniedCreate, isWindowsAccessDeniedRead, readLockRecord, } from './lock-record.js';
|
|
5
5
|
import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
|
|
6
6
|
import { LockOwnershipError, lockPathFor } from './with-lock.js';
|
|
@@ -91,6 +91,149 @@ async function writeExclusiveText(path, text) {
|
|
|
91
91
|
await handle.close();
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
|
+
// Lease owner records are staged in sibling files named
|
|
95
|
+
// `<lock file name>.<random UUID>.tmp` before they are linked or renamed into
|
|
96
|
+
// place: by createExclusiveText and by renewal, whose Windows branch uses
|
|
97
|
+
// writePrivateAtomic's default staging name of the same shape. Each writer
|
|
98
|
+
// removes its staging file when it finishes, but a process killed between
|
|
99
|
+
// creating the file and that cleanup leaves it behind for good, since nothing
|
|
100
|
+
// else ever reads that name. The sweep below removes only such leftovers.
|
|
101
|
+
const STAGING_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
102
|
+
// A staging file records the expiry of the lease it was about to publish,
|
|
103
|
+
// which is always in the future while its writer is alive. Requiring the
|
|
104
|
+
// expiry to be at least a lease TTL in the past, and never less than this
|
|
105
|
+
// floor, keeps a live writer's file safe even if wall clocks disagree.
|
|
106
|
+
const STAGING_SWEEP_MIN_AGE_MS = 10 * 60_000;
|
|
107
|
+
// Bounds the work one sweep does; any remainder is left for a later process.
|
|
108
|
+
const STAGING_SWEEP_MAX_CANDIDATES = 256;
|
|
109
|
+
// A complete owner record is under 100 bytes; anything far larger is not one.
|
|
110
|
+
const STAGING_SWEEP_MAX_BYTES = 4_096;
|
|
111
|
+
// Lock paths already swept by this process. Sweeping once per process keeps
|
|
112
|
+
// the directory listing off the hot path of every later acquisition.
|
|
113
|
+
const sweptLockPaths = new Set();
|
|
114
|
+
const pendingStagingSweeps = new Set();
|
|
115
|
+
let stagingSweepTestHooks;
|
|
116
|
+
/** Test-only sweep faults; not re-exported from the public fs entry point. */
|
|
117
|
+
export function setStagingSweepTestHooksForTest(hooks) {
|
|
118
|
+
stagingSweepTestHooks = hooks;
|
|
119
|
+
}
|
|
120
|
+
/** Tests only: wait for every staging sweep started so far to finish. */
|
|
121
|
+
export async function settleStagingSweepsForTest() {
|
|
122
|
+
while (pendingStagingSweeps.size > 0)
|
|
123
|
+
await Promise.all([...pendingStagingSweeps]);
|
|
124
|
+
}
|
|
125
|
+
/** Tests only: let the next acquisition of every lock path sweep again. */
|
|
126
|
+
export function forgetStagingSweepsForTest() {
|
|
127
|
+
sweptLockPaths.clear();
|
|
128
|
+
}
|
|
129
|
+
function isStagingName(name, lockName) {
|
|
130
|
+
const prefix = `${lockName}.`;
|
|
131
|
+
const suffix = '.tmp';
|
|
132
|
+
if (!name.startsWith(prefix) || !name.endsWith(suffix))
|
|
133
|
+
return false;
|
|
134
|
+
return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
|
|
135
|
+
}
|
|
136
|
+
function sameStagingFile(a, b) {
|
|
137
|
+
return (a.dev === b.dev &&
|
|
138
|
+
a.ino === b.ino &&
|
|
139
|
+
a.size === b.size &&
|
|
140
|
+
a.mtimeMs === b.mtimeMs &&
|
|
141
|
+
a.birthtimeMs === b.birthtimeMs);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Read the owner record a staging file holds, or undefined when the path is
|
|
145
|
+
* not a plain file holding exactly a complete `{ownerId, expiresAt}` record.
|
|
146
|
+
* Returns the lstat identity the record was read from, for the unlink fence.
|
|
147
|
+
*/
|
|
148
|
+
async function readStagedOwner(path) {
|
|
149
|
+
const before = await lstat(path);
|
|
150
|
+
if (!before.isFile() || before.isSymbolicLink())
|
|
151
|
+
return undefined;
|
|
152
|
+
if (before.size > STAGING_SWEEP_MAX_BYTES)
|
|
153
|
+
return undefined;
|
|
154
|
+
const handle = await open(path, 'r');
|
|
155
|
+
let text;
|
|
156
|
+
try {
|
|
157
|
+
// The path could be swapped between the lstat and the open; read only
|
|
158
|
+
// when the opened file is the one the lstat described.
|
|
159
|
+
if (!sameStagingFile(before, await handle.stat()))
|
|
160
|
+
return undefined;
|
|
161
|
+
text = await handle.readFile('utf8');
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
await handle.close();
|
|
165
|
+
}
|
|
166
|
+
let record;
|
|
167
|
+
try {
|
|
168
|
+
record = JSON.parse(text);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
if (!record || typeof record !== 'object' || Array.isArray(record))
|
|
174
|
+
return undefined;
|
|
175
|
+
const keys = Object.keys(record).sort();
|
|
176
|
+
if (keys.length !== 2 || keys[0] !== 'expiresAt' || keys[1] !== 'ownerId')
|
|
177
|
+
return undefined;
|
|
178
|
+
const { ownerId, expiresAt } = record;
|
|
179
|
+
if (typeof ownerId !== 'string' || !STAGING_UUID.test(ownerId))
|
|
180
|
+
return undefined;
|
|
181
|
+
if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt))
|
|
182
|
+
return undefined;
|
|
183
|
+
return { identity: before, expiresAt };
|
|
184
|
+
}
|
|
185
|
+
async function sweepAbandonedStaging(lockPath, ttlMs, now) {
|
|
186
|
+
const directory = dirname(lockPath);
|
|
187
|
+
const lockName = basename(lockPath);
|
|
188
|
+
const hooks = stagingSweepTestHooks;
|
|
189
|
+
const names = await (hooks?.readdir ?? readdir)(directory);
|
|
190
|
+
const candidates = names
|
|
191
|
+
.filter((name) => isStagingName(name, lockName))
|
|
192
|
+
.slice(0, STAGING_SWEEP_MAX_CANDIDATES);
|
|
193
|
+
const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
|
|
194
|
+
for (const name of candidates) {
|
|
195
|
+
const path = join(directory, name);
|
|
196
|
+
try {
|
|
197
|
+
// A file written within the margin belongs to a writer that may be
|
|
198
|
+
// alive, so don't even open it; the record's expiry still decides.
|
|
199
|
+
if (now() - (await lstat(path)).mtimeMs < marginMs)
|
|
200
|
+
continue;
|
|
201
|
+
const staged = await readStagedOwner(path);
|
|
202
|
+
if (!staged || !(staged.expiresAt < now() - marginMs))
|
|
203
|
+
continue;
|
|
204
|
+
if (hooks?.beforeUnlink)
|
|
205
|
+
await hooks.beforeUnlink(path);
|
|
206
|
+
// Remove only the file that was read: a name reused since then keeps
|
|
207
|
+
// its new contents. Inode numbers can be reused at once after an
|
|
208
|
+
// unlink, so the record is read again as well as the identity compared.
|
|
209
|
+
const current = await readStagedOwner(path);
|
|
210
|
+
if (!current ||
|
|
211
|
+
!sameStagingFile(staged.identity, current.identity) ||
|
|
212
|
+
!(current.expiresAt < now() - marginMs))
|
|
213
|
+
continue;
|
|
214
|
+
await (hooks?.unlink ?? unlink)(path);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// Each leftover is independent; a vanished or unreadable one is skipped.
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Start a background sweep of abandoned staging files beside `lockPath`, at
|
|
223
|
+
* most once per process per lock path. Called after this process acquires the
|
|
224
|
+
* lock, so no other cooperating process sweeps the same name at that moment.
|
|
225
|
+
* The sweep never delays or fails the acquisition: every error is ignored.
|
|
226
|
+
*/
|
|
227
|
+
function startStagingSweep(lockPath, ttlMs, now) {
|
|
228
|
+
if (sweptLockPaths.has(lockPath))
|
|
229
|
+
return;
|
|
230
|
+
sweptLockPaths.add(lockPath);
|
|
231
|
+
const sweep = Promise.resolve()
|
|
232
|
+
.then(() => sweepAbandonedStaging(lockPath, ttlMs, now))
|
|
233
|
+
.catch(() => { });
|
|
234
|
+
pendingStagingSweeps.add(sweep);
|
|
235
|
+
void sweep.finally(() => pendingStagingSweeps.delete(sweep));
|
|
236
|
+
}
|
|
94
237
|
const setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
|
|
95
238
|
const clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
|
|
96
239
|
// A concurrent contender renaming the freshly-created eviction-marker directory
|
|
@@ -970,6 +1113,7 @@ export async function acquireRefreshFileLockWithClock(options) {
|
|
|
970
1113
|
return null;
|
|
971
1114
|
}
|
|
972
1115
|
scheduleRenewal();
|
|
1116
|
+
startStagingSweep(lockPath, options.ttlMs, now);
|
|
973
1117
|
return {
|
|
974
1118
|
ownerId,
|
|
975
1119
|
whenLost: () => lostPromise,
|
package/dist/fs/with-lock.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type PrivateFileError } from './private-files.js';
|
|
1
2
|
import { acquireRefreshFileLock } from './refresh-file-lock.js';
|
|
2
3
|
export declare function lockPathFor(target: string, name: string): string;
|
|
3
4
|
export declare class LockContentionError extends Error {
|
|
@@ -32,6 +33,7 @@ export interface LockOptions {
|
|
|
32
33
|
onStep?: Parameters<typeof acquireRefreshFileLock>[0]['onStep'];
|
|
33
34
|
onRenewalTimer?: Parameters<typeof acquireRefreshFileLock>[0]['onRenewalTimer'];
|
|
34
35
|
}
|
|
36
|
+
export declare function isChangingLockRecord(error: unknown, target: string, name: string): error is PrivateFileError;
|
|
35
37
|
export declare function withLock<T>(target: string, options: LockOptions, fn: (lock: {
|
|
36
38
|
assertOwned(): Promise<void>;
|
|
37
39
|
}) => Promise<T>): Promise<T>;
|
package/dist/fs/with-lock.js
CHANGED
|
@@ -21,7 +21,7 @@ export class LockOwnershipError extends Error {
|
|
|
21
21
|
this.details = details;
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
|
-
function isChangingLockRecord(error, target, name) {
|
|
24
|
+
export function isChangingLockRecord(error, target, name) {
|
|
25
25
|
const path = resolve(lockPathFor(target, name));
|
|
26
26
|
const paths = [path, join(path, 'owner.json')];
|
|
27
27
|
return (((isWindowsSharingViolation(error) ||
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ValueDescriptor, type ValueOf, type ValueValidationOptions } from './descriptors.js';
|
|
2
|
+
export interface SettingDeclaration<D extends ValueDescriptor = ValueDescriptor> {
|
|
3
|
+
readonly value: D;
|
|
4
|
+
readonly default: ValueDescriptor extends D ? unknown : ValueOf<D>;
|
|
5
|
+
readonly hosts: 'both' | 'opencode' | 'pi' | string;
|
|
6
|
+
readonly overrides?: {
|
|
7
|
+
readonly host?: true;
|
|
8
|
+
readonly model?: true;
|
|
9
|
+
};
|
|
10
|
+
readonly project?: 'user-only' | 'allowed';
|
|
11
|
+
readonly legacy?: readonly {
|
|
12
|
+
readonly source: string;
|
|
13
|
+
readonly path: readonly string[];
|
|
14
|
+
}[];
|
|
15
|
+
}
|
|
16
|
+
type Declarations = Readonly<Record<string, SettingDeclaration>>;
|
|
17
|
+
export interface SettingsDefinition<S extends Declarations = Declarations> {
|
|
18
|
+
readonly plugin: string;
|
|
19
|
+
readonly settings: {
|
|
20
|
+
readonly [K in keyof S]: S[K] & {
|
|
21
|
+
readonly project: S[K] extends {
|
|
22
|
+
readonly project: infer P;
|
|
23
|
+
} ? P : 'project' extends keyof S[K] ? Exclude<S[K]['project'], undefined> | 'user-only' : 'user-only';
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export declare function defineSettings<const S extends Declarations>(definition: {
|
|
28
|
+
readonly plugin: string;
|
|
29
|
+
readonly settings: S;
|
|
30
|
+
}): SettingsDefinition<S>;
|
|
31
|
+
/** Internal helper: host names are reserved and never count as model ids. */
|
|
32
|
+
export declare function isOverrideKeyAllowed(overrides: NonNullable<SettingDeclaration['overrides']>, key: string): boolean;
|
|
33
|
+
/** Validate a file, update or map value, including any permitted override object. */
|
|
34
|
+
export declare function validateSettingValue(declaration: Pick<SettingDeclaration, 'value' | 'overrides'>, value: unknown, options?: ValueValidationOptions): boolean;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { deepFreeze, isJsonObject, validateValue, } from './descriptors.js';
|
|
2
|
+
export function defineSettings(definition) {
|
|
3
|
+
for (const [name, declaration] of Object.entries(definition.settings)) {
|
|
4
|
+
if (name === 'schema_version' || name === '$schema') {
|
|
5
|
+
throw new TypeError(`Reserved setting name: ${name}`);
|
|
6
|
+
}
|
|
7
|
+
if (!/^[a-z][a-z0-9_]*$/.test(name) || /\s/.test(name)) {
|
|
8
|
+
throw new TypeError(`Setting name must be snake_case: ${name}`);
|
|
9
|
+
}
|
|
10
|
+
if (name === 'sidebar' && declaration.value.kind !== 'object') {
|
|
11
|
+
throw new TypeError('The sidebar setting must use an object descriptor');
|
|
12
|
+
}
|
|
13
|
+
if (declaration.overrides !== undefined &&
|
|
14
|
+
(declaration.value.kind === 'object' ||
|
|
15
|
+
declaration.value.kind === 'record')) {
|
|
16
|
+
throw new TypeError(`Object and record settings cannot use overrides: ${name}`);
|
|
17
|
+
}
|
|
18
|
+
if (!Object.hasOwn(declaration, 'default') ||
|
|
19
|
+
!validateValue(declaration.value, declaration.default, {
|
|
20
|
+
completeObjects: true,
|
|
21
|
+
})) {
|
|
22
|
+
throw new TypeError(`Invalid default for setting: ${name}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// Copy before freezing so the caller can still use its original default values.
|
|
26
|
+
return deepFreeze({
|
|
27
|
+
plugin: definition.plugin,
|
|
28
|
+
settings: Object.fromEntries(Object.entries(definition.settings).map(([name, declaration]) => [
|
|
29
|
+
name,
|
|
30
|
+
structuredClone({
|
|
31
|
+
...declaration,
|
|
32
|
+
project: declaration.project ?? 'user-only',
|
|
33
|
+
}),
|
|
34
|
+
])),
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/** Internal helper: host names are reserved and never count as model ids. */
|
|
38
|
+
export function isOverrideKeyAllowed(overrides, key) {
|
|
39
|
+
if (key === 'default')
|
|
40
|
+
return true;
|
|
41
|
+
if (key === 'opencode' || key === 'pi')
|
|
42
|
+
return overrides.host === true;
|
|
43
|
+
return overrides.model === true;
|
|
44
|
+
}
|
|
45
|
+
/** Validate a file, update or map value, including any permitted override object. */
|
|
46
|
+
export function validateSettingValue(declaration, value, options = {}) {
|
|
47
|
+
if (declaration.overrides !== undefined && isJsonObject(value)) {
|
|
48
|
+
return Object.entries(value).every(([key, entry]) => isOverrideKeyAllowed(declaration.overrides ?? {}, key) &&
|
|
49
|
+
validateValue(declaration.value, entry, options));
|
|
50
|
+
}
|
|
51
|
+
return validateValue(declaration.value, value, options);
|
|
52
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
export type ValueDescriptor = {
|
|
2
|
+
readonly kind: 'boolean';
|
|
3
|
+
} | {
|
|
4
|
+
readonly kind: 'integer';
|
|
5
|
+
readonly min?: number;
|
|
6
|
+
readonly max?: number;
|
|
7
|
+
} | {
|
|
8
|
+
readonly kind: 'number';
|
|
9
|
+
readonly min?: number;
|
|
10
|
+
readonly max?: number;
|
|
11
|
+
} | {
|
|
12
|
+
readonly kind: 'string';
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: 'oneOf';
|
|
15
|
+
readonly values: readonly string[];
|
|
16
|
+
} | {
|
|
17
|
+
readonly kind: 'list';
|
|
18
|
+
readonly item: ValueDescriptor;
|
|
19
|
+
} | {
|
|
20
|
+
readonly kind: 'object';
|
|
21
|
+
readonly fields: Readonly<Record<string, ValueDescriptor>>;
|
|
22
|
+
} | {
|
|
23
|
+
readonly kind: 'record';
|
|
24
|
+
readonly value: ValueDescriptor;
|
|
25
|
+
};
|
|
26
|
+
type SettingsValue = boolean | number | string | SettingsValue[] | {
|
|
27
|
+
[key: string]: SettingsValue;
|
|
28
|
+
};
|
|
29
|
+
export type ValueOf<D extends ValueDescriptor> = ValueDescriptor extends D ? SettingsValue : D extends {
|
|
30
|
+
kind: 'boolean';
|
|
31
|
+
} ? boolean : D extends {
|
|
32
|
+
kind: 'integer' | 'number';
|
|
33
|
+
} ? number : D extends {
|
|
34
|
+
kind: 'string';
|
|
35
|
+
} ? string : D extends {
|
|
36
|
+
kind: 'oneOf';
|
|
37
|
+
values: infer V extends readonly string[];
|
|
38
|
+
} ? V[number] : D extends {
|
|
39
|
+
kind: 'list';
|
|
40
|
+
item: infer I extends ValueDescriptor;
|
|
41
|
+
} ? ValueOf<I>[] : D extends {
|
|
42
|
+
kind: 'object';
|
|
43
|
+
fields: infer F extends Readonly<Record<string, ValueDescriptor>>;
|
|
44
|
+
} ? {
|
|
45
|
+
-readonly [K in keyof F]: ValueOf<F[K]>;
|
|
46
|
+
} : D extends {
|
|
47
|
+
kind: 'record';
|
|
48
|
+
value: infer V extends ValueDescriptor;
|
|
49
|
+
} ? Record<string, ValueOf<V>> : never;
|
|
50
|
+
type Bounds = {
|
|
51
|
+
readonly min?: number;
|
|
52
|
+
readonly max?: number;
|
|
53
|
+
};
|
|
54
|
+
export declare function boolean(): Readonly<{
|
|
55
|
+
readonly kind: 'boolean';
|
|
56
|
+
}>;
|
|
57
|
+
export declare function integer({ min, max }?: Bounds): Readonly<{
|
|
58
|
+
readonly kind: 'integer';
|
|
59
|
+
readonly min: number | undefined;
|
|
60
|
+
readonly max: number | undefined;
|
|
61
|
+
}>;
|
|
62
|
+
export declare function number({ min, max }?: Bounds): Readonly<{
|
|
63
|
+
readonly kind: 'number';
|
|
64
|
+
readonly min: number | undefined;
|
|
65
|
+
readonly max: number | undefined;
|
|
66
|
+
}>;
|
|
67
|
+
export declare function string(): Readonly<{
|
|
68
|
+
readonly kind: 'string';
|
|
69
|
+
}>;
|
|
70
|
+
export declare function oneOf<const V extends readonly string[]>(values: V): Readonly<{
|
|
71
|
+
readonly kind: 'oneOf';
|
|
72
|
+
readonly values: Readonly<V>;
|
|
73
|
+
}>;
|
|
74
|
+
export declare function list<const D extends ValueDescriptor>(item: D): {
|
|
75
|
+
readonly kind: 'list';
|
|
76
|
+
readonly item: D;
|
|
77
|
+
};
|
|
78
|
+
export declare function object<const F extends Readonly<Record<string, ValueDescriptor>>>(fields: F): {
|
|
79
|
+
readonly kind: 'object';
|
|
80
|
+
readonly fields: F;
|
|
81
|
+
};
|
|
82
|
+
export declare function record<const D extends ValueDescriptor>(value: D): {
|
|
83
|
+
readonly kind: 'record';
|
|
84
|
+
readonly value: D;
|
|
85
|
+
};
|
|
86
|
+
/** Internal validation policy shared by file readers, updates and migration maps. */
|
|
87
|
+
export interface ValueValidationOptions {
|
|
88
|
+
readonly completeObjects?: boolean;
|
|
89
|
+
readonly allowUnknownFields?: boolean;
|
|
90
|
+
}
|
|
91
|
+
/** JSON objects exclude arrays and objects such as Date that serialize differently. */
|
|
92
|
+
export declare function isJsonObject(value: unknown): value is Record<string, unknown>;
|
|
93
|
+
/** Missing fields can be filled from lower levels, but list and record objects must be complete. */
|
|
94
|
+
export declare function validateValue(descriptor: ValueDescriptor, value: unknown, options?: ValueValidationOptions): boolean;
|
|
95
|
+
/** Internal helper; definitions and descriptor payloads are immutable at runtime. */
|
|
96
|
+
export declare function deepFreeze<T>(value: T): T;
|
|
97
|
+
export {};
|