@cortexkit/common-auth 0.44.0 → 0.46.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 +159 -11
- package/dist/fs/with-lock.d.ts +2 -0
- package/dist/fs/with-lock.js +1 -1
- package/dist/routing-accessor/index.d.ts +17 -0
- package/dist/routing-accessor/index.js +13 -0
- 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
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
function descriptorSchema(descriptor, completeObjects = false) {
|
|
2
|
+
switch (descriptor.kind) {
|
|
3
|
+
case 'boolean':
|
|
4
|
+
case 'string':
|
|
5
|
+
return { type: descriptor.kind };
|
|
6
|
+
case 'integer':
|
|
7
|
+
case 'number':
|
|
8
|
+
return {
|
|
9
|
+
type: descriptor.kind,
|
|
10
|
+
...(descriptor.min !== undefined ? { minimum: descriptor.min } : {}),
|
|
11
|
+
...(descriptor.max !== undefined ? { maximum: descriptor.max } : {}),
|
|
12
|
+
};
|
|
13
|
+
case 'oneOf':
|
|
14
|
+
return { enum: [...descriptor.values] };
|
|
15
|
+
case 'list':
|
|
16
|
+
return { type: 'array', items: descriptorSchema(descriptor.item, true) };
|
|
17
|
+
case 'object':
|
|
18
|
+
return {
|
|
19
|
+
type: 'object',
|
|
20
|
+
properties: Object.fromEntries(Object.entries(descriptor.fields).map(([name, field]) => [
|
|
21
|
+
name,
|
|
22
|
+
descriptorSchema(field, completeObjects),
|
|
23
|
+
])),
|
|
24
|
+
additionalProperties: false,
|
|
25
|
+
// Objects merge field by field, except in lists and records, which replace whole values.
|
|
26
|
+
...(completeObjects
|
|
27
|
+
? { required: Object.keys(descriptor.fields) }
|
|
28
|
+
: {}),
|
|
29
|
+
};
|
|
30
|
+
case 'record':
|
|
31
|
+
return {
|
|
32
|
+
type: 'object',
|
|
33
|
+
additionalProperties: descriptorSchema(descriptor.value, true),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function settingSchema(declaration) {
|
|
38
|
+
const value = descriptorSchema(declaration.value);
|
|
39
|
+
if (declaration.overrides === undefined)
|
|
40
|
+
return value;
|
|
41
|
+
const { host, model } = declaration.overrides;
|
|
42
|
+
const properties = { default: value };
|
|
43
|
+
if (host) {
|
|
44
|
+
properties.opencode = value;
|
|
45
|
+
properties.pi = value;
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
anyOf: [
|
|
49
|
+
value,
|
|
50
|
+
{
|
|
51
|
+
type: 'object',
|
|
52
|
+
properties,
|
|
53
|
+
additionalProperties: model ? value : false,
|
|
54
|
+
...(model && !host
|
|
55
|
+
? { propertyNames: { not: { enum: ['opencode', 'pi'] } } }
|
|
56
|
+
: {}),
|
|
57
|
+
},
|
|
58
|
+
],
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Generate the plugin's JSON Schema deterministically from its settings definition.
|
|
63
|
+
* Plugins ship the generated schema and check their parsed shipped file with:
|
|
64
|
+
* `expect(shippedSchema).toEqual(settingsJsonSchema(definition))`.
|
|
65
|
+
*/
|
|
66
|
+
export function settingsJsonSchema(definition) {
|
|
67
|
+
const properties = {
|
|
68
|
+
schema_version: { type: 'integer', minimum: 1 },
|
|
69
|
+
$schema: { type: 'string' },
|
|
70
|
+
...Object.fromEntries(Object.entries(definition.settings).map(([name, declaration]) => [
|
|
71
|
+
name,
|
|
72
|
+
settingSchema(declaration),
|
|
73
|
+
])),
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
|
77
|
+
type: 'object',
|
|
78
|
+
properties,
|
|
79
|
+
additionalProperties: false,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type SettingsDefinition } from './define.js';
|
|
2
|
+
import { type SettingsParseResult } from './parse.js';
|
|
3
|
+
export type ReportReason = 'unknown-key' | 'override-not-allowed' | 'user-only-in-project' | 'invalid-value' | 'invalid-schema-version' | 'newer-version-key-ignored' | 'duplicate-key' | 'unparseable' | 'unreadable';
|
|
4
|
+
export interface ReportEntry {
|
|
5
|
+
file: {
|
|
6
|
+
kind: 'user' | 'project' | 'legacy-project';
|
|
7
|
+
path: string;
|
|
8
|
+
};
|
|
9
|
+
keyPath: string[];
|
|
10
|
+
reason: ReportReason;
|
|
11
|
+
detail?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface SettingsSnapshot {
|
|
14
|
+
file: ReportEntry['file'];
|
|
15
|
+
/** Only usable values remain; override objects retain their allowed keys. */
|
|
16
|
+
settings: Record<string, unknown>;
|
|
17
|
+
entries: ReportEntry[];
|
|
18
|
+
schemaVersion: number;
|
|
19
|
+
newer: boolean;
|
|
20
|
+
hasDuplicates: boolean;
|
|
21
|
+
parsed: SettingsParseResult;
|
|
22
|
+
}
|
|
23
|
+
/** Validate all overrides now, including values for hosts not requested later. */
|
|
24
|
+
export declare function buildSettingsSnapshot(definition: SettingsDefinition, file: ReportEntry['file'], parsed: SettingsParseResult): SettingsSnapshot;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { isOverrideKeyAllowed } from './define.js';
|
|
2
|
+
import { isJsonObject, validateValue, } from './descriptors.js';
|
|
3
|
+
import { defineSettingsKey } from './parse.js';
|
|
4
|
+
/** Validate all children even when a list or record will be skipped as a whole. */
|
|
5
|
+
function validateFileValue(descriptor, value, keyPath, completeObjects, unknownReason, report) {
|
|
6
|
+
const invalid = () => {
|
|
7
|
+
report(keyPath, 'invalid-value');
|
|
8
|
+
return { valid: false };
|
|
9
|
+
};
|
|
10
|
+
if (descriptor.kind === 'object') {
|
|
11
|
+
if (!isJsonObject(value))
|
|
12
|
+
return invalid();
|
|
13
|
+
const cleaned = {};
|
|
14
|
+
let valid = true;
|
|
15
|
+
for (const [key, field] of Object.entries(value)) {
|
|
16
|
+
if (!Object.hasOwn(descriptor.fields, key)) {
|
|
17
|
+
report([...keyPath, key], unknownReason);
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const result = validateFileValue(descriptor.fields[key], field, [...keyPath, key], completeObjects, unknownReason, report);
|
|
21
|
+
if (result.valid)
|
|
22
|
+
defineSettingsKey(cleaned, key, result.value);
|
|
23
|
+
else
|
|
24
|
+
valid = false;
|
|
25
|
+
}
|
|
26
|
+
if (completeObjects) {
|
|
27
|
+
for (const key of Object.keys(descriptor.fields)) {
|
|
28
|
+
if (!Object.hasOwn(value, key)) {
|
|
29
|
+
report([...keyPath, key], 'invalid-value');
|
|
30
|
+
valid = false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Partial objects keep valid siblings; resolution supplies skipped fields.
|
|
35
|
+
return valid || !completeObjects
|
|
36
|
+
? { valid: true, value: cleaned }
|
|
37
|
+
: { valid: false };
|
|
38
|
+
}
|
|
39
|
+
if (descriptor.kind === 'list') {
|
|
40
|
+
if (!Array.isArray(value))
|
|
41
|
+
return invalid();
|
|
42
|
+
const cleaned = [];
|
|
43
|
+
let valid = true;
|
|
44
|
+
for (const [index, item] of value.entries()) {
|
|
45
|
+
const result = validateFileValue(descriptor.item, item, [...keyPath, String(index)], true, unknownReason, report);
|
|
46
|
+
if (result.valid)
|
|
47
|
+
cleaned.push(result.value);
|
|
48
|
+
else
|
|
49
|
+
valid = false;
|
|
50
|
+
}
|
|
51
|
+
return valid ? { valid: true, value: cleaned } : { valid: false };
|
|
52
|
+
}
|
|
53
|
+
if (descriptor.kind === 'record') {
|
|
54
|
+
if (!isJsonObject(value))
|
|
55
|
+
return invalid();
|
|
56
|
+
const cleaned = {};
|
|
57
|
+
let valid = true;
|
|
58
|
+
for (const [key, item] of Object.entries(value)) {
|
|
59
|
+
const result = validateFileValue(descriptor.value, item, [...keyPath, key], true, unknownReason, report);
|
|
60
|
+
if (result.valid)
|
|
61
|
+
defineSettingsKey(cleaned, key, result.value);
|
|
62
|
+
else
|
|
63
|
+
valid = false;
|
|
64
|
+
}
|
|
65
|
+
return valid ? { valid: true, value: cleaned } : { valid: false };
|
|
66
|
+
}
|
|
67
|
+
return validateValue(descriptor, value) ? { valid: true, value } : invalid();
|
|
68
|
+
}
|
|
69
|
+
/** Validate all overrides now, including values for hosts not requested later. */
|
|
70
|
+
export function buildSettingsSnapshot(definition, file, parsed) {
|
|
71
|
+
const entries = [];
|
|
72
|
+
const reported = new Set();
|
|
73
|
+
const report = (keyPath, reason) => {
|
|
74
|
+
const identity = JSON.stringify([keyPath, reason]);
|
|
75
|
+
if (reported.has(identity))
|
|
76
|
+
return;
|
|
77
|
+
reported.add(identity);
|
|
78
|
+
entries.push({ file: { ...file }, keyPath: [...keyPath], reason });
|
|
79
|
+
};
|
|
80
|
+
const snapshot = {
|
|
81
|
+
file: { ...file },
|
|
82
|
+
settings: {},
|
|
83
|
+
entries,
|
|
84
|
+
schemaVersion: 1,
|
|
85
|
+
newer: false,
|
|
86
|
+
hasDuplicates: parsed.parseable && parsed.hasDuplicates,
|
|
87
|
+
parsed,
|
|
88
|
+
};
|
|
89
|
+
if (!parsed.parseable) {
|
|
90
|
+
report([], 'unparseable');
|
|
91
|
+
return snapshot;
|
|
92
|
+
}
|
|
93
|
+
for (const keyPath of parsed.duplicateKeyPaths)
|
|
94
|
+
report(keyPath, 'duplicate-key');
|
|
95
|
+
const input = parsed.value;
|
|
96
|
+
if (Object.hasOwn(input, 'schema_version')) {
|
|
97
|
+
const version = input.schema_version;
|
|
98
|
+
if (typeof version === 'number' &&
|
|
99
|
+
Number.isInteger(version) &&
|
|
100
|
+
version >= 1) {
|
|
101
|
+
snapshot.schemaVersion = version;
|
|
102
|
+
snapshot.newer = version > 1;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
report(['schema_version'], 'invalid-schema-version');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const unknownReason = snapshot.newer
|
|
109
|
+
? 'newer-version-key-ignored'
|
|
110
|
+
: 'unknown-key';
|
|
111
|
+
for (const [name, value] of Object.entries(input)) {
|
|
112
|
+
if (name === 'schema_version' || name === '$schema')
|
|
113
|
+
continue;
|
|
114
|
+
if (!Object.hasOwn(definition.settings, name)) {
|
|
115
|
+
report([name], unknownReason);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const declaration = definition.settings[name];
|
|
119
|
+
if (!declaration)
|
|
120
|
+
continue;
|
|
121
|
+
if (file.kind !== 'user' && declaration.project !== 'allowed') {
|
|
122
|
+
report([name], 'user-only-in-project');
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (isJsonObject(value) && declaration.overrides !== undefined) {
|
|
126
|
+
const overrides = {};
|
|
127
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
128
|
+
if (!isOverrideKeyAllowed(declaration.overrides, key)) {
|
|
129
|
+
report([name, key], 'override-not-allowed');
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const result = validateFileValue(declaration.value, entry, [name, key], false, unknownReason, report);
|
|
133
|
+
if (result.valid)
|
|
134
|
+
defineSettingsKey(overrides, key, result.value);
|
|
135
|
+
}
|
|
136
|
+
defineSettingsKey(snapshot.settings, name, overrides);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (isJsonObject(value) &&
|
|
140
|
+
declaration.value.kind !== 'object' &&
|
|
141
|
+
declaration.value.kind !== 'record') {
|
|
142
|
+
report([name], 'override-not-allowed');
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const result = validateFileValue(declaration.value, value, [name], false, unknownReason, report);
|
|
146
|
+
if (result.valid)
|
|
147
|
+
defineSettingsKey(snapshot.settings, name, result.value);
|
|
148
|
+
}
|
|
149
|
+
return snapshot;
|
|
150
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SettingsDefinition } from './define.js';
|
|
2
|
+
import { type SettingsEdit, type UpdateResult } from './edit.js';
|
|
3
|
+
import type { OpenSettingsOptions } from './handle.js';
|
|
4
|
+
import type { GetOptions } from './resolve.js';
|
|
5
|
+
/** Lock the canonical user file so symlink aliases serialize the same edits. */
|
|
6
|
+
export declare function updateSettings(definition: SettingsDefinition, options: OpenSettingsOptions, edits: readonly SettingsEdit[], context: Pick<GetOptions, 'host' | 'model'>): Promise<UpdateResult>;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { basename, dirname, join } from 'node:path';
|
|
2
|
+
import { ensurePrivateDirectory } from '../fs/private-files.js';
|
|
3
|
+
import { withLock } from '../fs/with-lock.js';
|
|
4
|
+
import { applySettingsEdits, } from './edit.js';
|
|
5
|
+
import { SettingsFs } from './fs.js';
|
|
6
|
+
import { rethrowSettingsLockError } from './lock-errors.js';
|
|
7
|
+
import { parseSettings } from './parse.js';
|
|
8
|
+
import { SettingsRefusal } from './refusal.js';
|
|
9
|
+
import { writeSettings } from './write.js';
|
|
10
|
+
const SETTINGS_WRITE_LOCK = Object.freeze({
|
|
11
|
+
name: 'settings-write',
|
|
12
|
+
ttlMs: 10_000,
|
|
13
|
+
timeoutMs: 2_000,
|
|
14
|
+
renew: true,
|
|
15
|
+
});
|
|
16
|
+
function unavailable(file, cause) {
|
|
17
|
+
throw new SettingsRefusal('settings-unavailable', `Settings file is unavailable: ${file}`, { cause });
|
|
18
|
+
}
|
|
19
|
+
async function writeTarget(file) {
|
|
20
|
+
try {
|
|
21
|
+
return await SettingsFs.realpath(file);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error.code !== 'ENOENT')
|
|
25
|
+
unavailable(file, error);
|
|
26
|
+
try {
|
|
27
|
+
await SettingsFs.lstat(file);
|
|
28
|
+
}
|
|
29
|
+
catch (lstatError) {
|
|
30
|
+
if (lstatError.code !== 'ENOENT')
|
|
31
|
+
unavailable(file, lstatError);
|
|
32
|
+
try {
|
|
33
|
+
return join(await SettingsFs.realpath(dirname(file)), basename(file));
|
|
34
|
+
}
|
|
35
|
+
catch (parentError) {
|
|
36
|
+
unavailable(file, parentError);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// A directory entry whose realpath is missing is a dangling symlink.
|
|
40
|
+
unavailable(file, error);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Lock the canonical user file so symlink aliases serialize the same edits. */
|
|
44
|
+
export async function updateSettings(definition, options, edits, context) {
|
|
45
|
+
if (options.separateInstall) {
|
|
46
|
+
throw new SettingsRefusal('settings-unavailable', 'Settings are unavailable for a separate install');
|
|
47
|
+
}
|
|
48
|
+
const folder = dirname(options.file);
|
|
49
|
+
try {
|
|
50
|
+
if (!options.createMissing)
|
|
51
|
+
await SettingsFs.stat(folder);
|
|
52
|
+
else if (process.platform === 'win32')
|
|
53
|
+
await ensurePrivateDirectory(folder);
|
|
54
|
+
else
|
|
55
|
+
await SettingsFs.mkdir(folder, { recursive: true, mode: 0o700 });
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
unavailable(options.file, error);
|
|
59
|
+
}
|
|
60
|
+
const target = await writeTarget(options.file);
|
|
61
|
+
let settled;
|
|
62
|
+
try {
|
|
63
|
+
return await withLock(target, {
|
|
64
|
+
...SETTINGS_WRITE_LOCK,
|
|
65
|
+
timeoutMs: options.lockTimeoutMs ?? SETTINGS_WRITE_LOCK.timeoutMs,
|
|
66
|
+
}, async (lock) => {
|
|
67
|
+
try {
|
|
68
|
+
if ((await writeTarget(options.file)) !== target) {
|
|
69
|
+
throw new SettingsRefusal('settings-busy', `Settings target changed while locking: ${options.file}`);
|
|
70
|
+
}
|
|
71
|
+
let source;
|
|
72
|
+
let existingMode;
|
|
73
|
+
let missing = false;
|
|
74
|
+
try {
|
|
75
|
+
source = await SettingsFs.readFile(target, 'utf8');
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error.code !== 'ENOENT' ||
|
|
79
|
+
!options.createMissing)
|
|
80
|
+
unavailable(target, error);
|
|
81
|
+
missing = true;
|
|
82
|
+
source = '';
|
|
83
|
+
}
|
|
84
|
+
if (!missing) {
|
|
85
|
+
try {
|
|
86
|
+
existingMode = (await SettingsFs.stat(target)).mode;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
unavailable(target, error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const parsed = parseSettings(source);
|
|
93
|
+
if (!parsed.parseable || parsed.hasDuplicates) {
|
|
94
|
+
throw new SettingsRefusal('settings-unparseable', 'Settings must be an object without duplicate keys');
|
|
95
|
+
}
|
|
96
|
+
const version = parsed.value.schema_version;
|
|
97
|
+
if (Number.isInteger(version) && version > 1) {
|
|
98
|
+
throw new SettingsRefusal('settings-newer-version', 'Settings were written by a newer version');
|
|
99
|
+
}
|
|
100
|
+
if (!parsed.tree) {
|
|
101
|
+
source = `${parsed.hasBom ? '\uFEFF' : ''}// ${definition.plugin} settings\n{\n "schema_version": 1\n}\n`;
|
|
102
|
+
}
|
|
103
|
+
const edited = applySettingsEdits(definition, source, edits, context);
|
|
104
|
+
const result = edited.outcome === 'unchanged'
|
|
105
|
+
? { outcome: 'unchanged' }
|
|
106
|
+
: await writeSettings({
|
|
107
|
+
target,
|
|
108
|
+
text: edited.text,
|
|
109
|
+
hasBom: edited.hasBom,
|
|
110
|
+
existingMode,
|
|
111
|
+
lock,
|
|
112
|
+
logger: options.log,
|
|
113
|
+
});
|
|
114
|
+
settled = { outcome: 'fulfilled', result };
|
|
115
|
+
return result;
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
settled = { outcome: 'rejected', error };
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (!settled)
|
|
125
|
+
rethrowSettingsLockError(error, target, SETTINGS_WRITE_LOCK.name);
|
|
126
|
+
// Release runs after the callback; it cannot undo a settings write or refusal.
|
|
127
|
+
if (settled.outcome === 'fulfilled' || error !== settled.error) {
|
|
128
|
+
try {
|
|
129
|
+
options.log.warn('Settings lock release failed', { target, error });
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// A logger failure must not replace the callback's own outcome either.
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (settled.outcome === 'rejected')
|
|
136
|
+
throw settled.error;
|
|
137
|
+
return settled.result;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
interface SettingsWriteOptions {
|
|
2
|
+
target: string;
|
|
3
|
+
/** Final edited text, without the leading BOM stripped by the reader. */
|
|
4
|
+
text: string;
|
|
5
|
+
hasBom: boolean;
|
|
6
|
+
/** Absent for a missing target; otherwise the existing file's stat mode. */
|
|
7
|
+
existingMode?: number;
|
|
8
|
+
lock: {
|
|
9
|
+
assertOwned(): Promise<void>;
|
|
10
|
+
};
|
|
11
|
+
logger?: {
|
|
12
|
+
warn(message: string, details?: Record<string, unknown>): void;
|
|
13
|
+
};
|
|
14
|
+
platform?: NodeJS.Platform;
|
|
15
|
+
}
|
|
16
|
+
type StepHook = (step: 'staged', paths: {
|
|
17
|
+
target: string;
|
|
18
|
+
temp: string;
|
|
19
|
+
}) => void | Promise<void>;
|
|
20
|
+
/** Internal test hook, deliberately absent from the package entry point. */
|
|
21
|
+
export declare function setSettingsWriteStepHookForTest(hook?: StepHook): void;
|
|
22
|
+
/** Publish already validated edits while the caller holds the target's lock. */
|
|
23
|
+
export declare function writeSettings(options: SettingsWriteOptions): Promise<{
|
|
24
|
+
outcome: 'updated';
|
|
25
|
+
}>;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { SettingsFs } from './fs.js';
|
|
3
|
+
import { SettingsRefusal } from './refusal.js';
|
|
4
|
+
let stepHook;
|
|
5
|
+
const HARD_LINK_UNSUPPORTED = new Set([
|
|
6
|
+
'EPERM',
|
|
7
|
+
'ENOTSUP',
|
|
8
|
+
'EOPNOTSUPP',
|
|
9
|
+
'ENOSYS',
|
|
10
|
+
]);
|
|
11
|
+
/** Internal test hook, deliberately absent from the package entry point. */
|
|
12
|
+
export function setSettingsWriteStepHookForTest(hook) {
|
|
13
|
+
stepHook = hook;
|
|
14
|
+
}
|
|
15
|
+
/** Publish already validated edits while the caller holds the target's lock. */
|
|
16
|
+
export async function writeSettings(options) {
|
|
17
|
+
const { target, text, hasBom, existingMode, lock, logger } = options;
|
|
18
|
+
const platform = options.platform ?? process.platform;
|
|
19
|
+
const temp = `${target}.${randomUUID()}.tmp`;
|
|
20
|
+
let staged = false;
|
|
21
|
+
let published = false;
|
|
22
|
+
try {
|
|
23
|
+
const file = await SettingsFs.open(temp, 'wx', 0o644);
|
|
24
|
+
staged = true;
|
|
25
|
+
try {
|
|
26
|
+
await file.writeFile(`${hasBom ? '\uFEFF' : ''}${text}`, 'utf8');
|
|
27
|
+
if (platform !== 'win32' && existingMode !== undefined) {
|
|
28
|
+
await file.chmod(existingMode & 0o777);
|
|
29
|
+
}
|
|
30
|
+
await file.sync();
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
await file.close();
|
|
34
|
+
}
|
|
35
|
+
await stepHook?.('staged', { target, temp });
|
|
36
|
+
await lock.assertOwned();
|
|
37
|
+
if (existingMode !== undefined) {
|
|
38
|
+
try {
|
|
39
|
+
await SettingsFs.rename(temp, target);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (platform === 'win32' &&
|
|
43
|
+
['EPERM', 'EACCES', 'EBUSY'].includes(error.code ?? '')) {
|
|
44
|
+
throw new SettingsRefusal('settings-busy', `Settings file is busy: ${target}`, { cause: error });
|
|
45
|
+
}
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
published = true;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
try {
|
|
52
|
+
// A hard link never replaces a file created since the locked read.
|
|
53
|
+
await SettingsFs.link(temp, target);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
const code = error.code ?? '';
|
|
57
|
+
if (code === 'EEXIST') {
|
|
58
|
+
throw new SettingsRefusal('settings-busy', `Settings file appeared before publication: ${target}`, { cause: error });
|
|
59
|
+
}
|
|
60
|
+
// Some filesystems (FAT, exFAT, some network and user-space mounts) have no
|
|
61
|
+
// hard links. A non-atomic create could expose a half-written file, so
|
|
62
|
+
// refuse instead of falling back.
|
|
63
|
+
if (HARD_LINK_UNSUPPORTED.has(code)) {
|
|
64
|
+
throw new SettingsRefusal('settings-unavailable', `Settings file cannot be created on this filesystem: ${target}`, { cause: error });
|
|
65
|
+
}
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
published = true;
|
|
69
|
+
try {
|
|
70
|
+
await SettingsFs.unlink(temp);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
// Publication succeeded; an orphaned temp must not turn it into a refusal.
|
|
74
|
+
logger?.warn('Settings temp cleanup failed after publication', {
|
|
75
|
+
target,
|
|
76
|
+
temp,
|
|
77
|
+
error,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return { outcome: 'updated' };
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
if (staged && !published) {
|
|
85
|
+
await SettingsFs.unlink(temp).catch(() => { });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -17,7 +17,7 @@ export declare class SetupCommandError extends Error {
|
|
|
17
17
|
});
|
|
18
18
|
}
|
|
19
19
|
/** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
|
|
20
|
-
export declare function setupEnrollmentLine({ host, outcome, access
|
|
20
|
+
export declare function setupEnrollmentLine({ host, outcome, access }: SetupHostEnrollment, grantFallback?: 'setup' | 'plugin'): string;
|
|
21
21
|
/**
|
|
22
22
|
* Remember which hosts a failed setup left connected to the vault, against the
|
|
23
23
|
* thrown value. Only objects can carry a record; a thrown primitive is left as
|
|
@@ -48,8 +48,9 @@ const OUTCOME_TEXT = {
|
|
|
48
48
|
unknown: 'unknown, check with ck auth status',
|
|
49
49
|
};
|
|
50
50
|
/** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
|
|
51
|
-
export function setupEnrollmentLine({ host, outcome, access,
|
|
52
|
-
|
|
51
|
+
export function setupEnrollmentLine({ host, outcome, access }, grantFallback = 'setup') {
|
|
52
|
+
const lines = access ? enrollmentAccessLines(access, grantFallback) : [];
|
|
53
|
+
return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${lines.length ? ` — ${lines.join('\n')}` : ''}`;
|
|
53
54
|
}
|
|
54
55
|
// Outcomes recorded against the value a failed `runSetup` threw. A WeakMap
|
|
55
56
|
// keeps the thrown value itself untouched: setup never reads, rewrites or
|
package/dist/setup/command.js
CHANGED
|
@@ -26,6 +26,10 @@ function validatePlugin(plugin) {
|
|
|
26
26
|
if (host.requestedGrants !== undefined &&
|
|
27
27
|
!validEnrollmentRequestedGrants(host.requestedGrants))
|
|
28
28
|
throw new Error('invalid Claustrum enrollment requested grants');
|
|
29
|
+
if (host.grantFallback !== undefined &&
|
|
30
|
+
host.grantFallback !== 'setup' &&
|
|
31
|
+
host.grantFallback !== 'plugin')
|
|
32
|
+
throw new Error('invalid Claustrum enrollment grant fallback');
|
|
29
33
|
}
|
|
30
34
|
}
|
|
31
35
|
/**
|
|
@@ -264,7 +268,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
|
|
|
264
268
|
const report = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
|
|
265
269
|
recordSetupEnrollment(error, report);
|
|
266
270
|
for (const entry of report)
|
|
267
|
-
printLine(terminal, setupEnrollmentLine(entry));
|
|
271
|
+
printLine(terminal, setupEnrollmentLine(entry, plugin.vault.hosts[entry.host].grantFallback));
|
|
268
272
|
}
|
|
269
273
|
catch { }
|
|
270
274
|
throw error;
|
package/dist/setup/enroll.js
CHANGED
|
@@ -55,7 +55,7 @@ function approveCommand(requestId, name) {
|
|
|
55
55
|
export async function connectSetupHost(plugin, host, io, terminal, fence) {
|
|
56
56
|
if (hasVaultHost())
|
|
57
57
|
throw new Error(VAULT_HOST_CONNECT_REFUSAL);
|
|
58
|
-
const { name, displayName, requestedGrants, paths: input, } = plugin.vault.hosts[host];
|
|
58
|
+
const { name, displayName, requestedGrants, grantFallback, paths: input, } = plugin.vault.hosts[host];
|
|
59
59
|
const paths = hostEnrollmentPaths(input);
|
|
60
60
|
await fence();
|
|
61
61
|
const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
|
|
@@ -89,7 +89,7 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
|
|
|
89
89
|
printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
|
|
90
90
|
const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
|
|
91
91
|
if (access)
|
|
92
|
-
for (const line of enrollmentAccessLines(access))
|
|
92
|
+
for (const line of enrollmentAccessLines(access, grantFallback))
|
|
93
93
|
printLine(terminal, line);
|
|
94
94
|
return access;
|
|
95
95
|
}
|
|
@@ -105,7 +105,7 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
|
|
|
105
105
|
printLine(terminal, `Connected ${host} to Claustrum.`);
|
|
106
106
|
const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
|
|
107
107
|
if (access)
|
|
108
|
-
for (const line of enrollmentAccessLines(access))
|
|
108
|
+
for (const line of enrollmentAccessLines(access, grantFallback))
|
|
109
109
|
printLine(terminal, line);
|
|
110
110
|
return access;
|
|
111
111
|
}
|
|
@@ -4,4 +4,4 @@ import type { SetupEnrollmentAccess } from './types.js';
|
|
|
4
4
|
export declare function confirmEnrollmentAccess(client: Pick<ClaustrumEnrollmentConnection, 'listScoped'>, status: Extract<ClaustrumEnrollmentStatus, {
|
|
5
5
|
state: 'approved';
|
|
6
6
|
}>, tokenPath: string, configuredGrants: ReadonlyArray<ClaustrumRequestedGrant> | undefined): Promise<SetupEnrollmentAccess | undefined>;
|
|
7
|
-
export declare function enrollmentAccessLines(access: SetupEnrollmentAccess): string[];
|
|
7
|
+
export declare function enrollmentAccessLines(access: SetupEnrollmentAccess, grantFallback?: 'setup' | 'plugin'): string[];
|
|
@@ -17,11 +17,17 @@ export async function confirmEnrollmentAccess(client, status, tokenPath, configu
|
|
|
17
17
|
grantCommand: `ck auth grant --principal ${shellArgument(`enrolled:${status.approvedName}`)} --selector-kind ${grant.selector.exact === undefined ? 'category' : 'exact'} --selector ${shellArgument(grant.selector.exact ?? grant.selector.category)} --operation ${grant.operation}`,
|
|
18
18
|
}),
|
|
19
19
|
}));
|
|
20
|
+
const access = {
|
|
21
|
+
grants,
|
|
22
|
+
...(status.requestedGrantsStatus !== undefined && {
|
|
23
|
+
requestedGrantsStatus: status.requestedGrantsStatus,
|
|
24
|
+
}),
|
|
25
|
+
};
|
|
20
26
|
if (status.requestedGrantsStatus === 'dropped')
|
|
21
|
-
return { state: 'older-vault'
|
|
27
|
+
return { ...access, state: 'older-vault' };
|
|
22
28
|
try {
|
|
23
29
|
if (!client.listScoped)
|
|
24
|
-
return { state: 'unconfirmed'
|
|
30
|
+
return { ...access, state: 'unconfirmed' };
|
|
25
31
|
const { token } = await readClaustrumEnrollmentToken(tokenPath);
|
|
26
32
|
const inventory = await client.listScoped(token);
|
|
27
33
|
const confirmed = grants.map((entry) => ({
|
|
@@ -32,6 +38,7 @@ export async function confirmEnrollmentAccess(client, status, tokenPath, configu
|
|
|
32
38
|
: row.categories.includes(entry.grant.selector.category))).length,
|
|
33
39
|
}));
|
|
34
40
|
return {
|
|
41
|
+
...access,
|
|
35
42
|
state: confirmed.every((entry) => entry.reachableLogins > 0)
|
|
36
43
|
? 'reachable'
|
|
37
44
|
: confirmed.some((entry) => entry.reachableLogins > 0)
|
|
@@ -47,10 +54,12 @@ export async function confirmEnrollmentAccess(client, status, tokenPath, configu
|
|
|
47
54
|
}
|
|
48
55
|
catch {
|
|
49
56
|
// A listing failure cannot undo approval, and its error may contain secrets.
|
|
50
|
-
return { state: 'unconfirmed'
|
|
57
|
+
return { ...access, state: 'unconfirmed' };
|
|
51
58
|
}
|
|
52
59
|
}
|
|
53
|
-
export function enrollmentAccessLines(access) {
|
|
60
|
+
export function enrollmentAccessLines(access, grantFallback = 'setup') {
|
|
61
|
+
if (grantFallback === 'plugin' && access.requestedGrantsStatus !== 'sent')
|
|
62
|
+
return [];
|
|
54
63
|
const lines = [];
|
|
55
64
|
const remedy = access.grants.some((entry) => entry.grantCommand)
|
|
56
65
|
? 'run:'
|
package/dist/setup/types.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ export type SetupEnvironment = Record<string, string | undefined>;
|
|
|
13
13
|
export type SetupEnrollmentOutcome = 'enrolled' | 'not-enrolled' | 'unknown';
|
|
14
14
|
export interface SetupEnrollmentAccess {
|
|
15
15
|
state: 'reachable' | 'no-logins' | 'partial' | 'older-vault' | 'unconfirmed';
|
|
16
|
+
/** Whether grants were sent with the proposal or dropped for an older vault. Absent for enrollments made before 0.44.0. */
|
|
17
|
+
requestedGrantsStatus?: 'sent' | 'dropped';
|
|
16
18
|
/** One result per requested grant, in proposal order. No count means unknown. */
|
|
17
19
|
grants: readonly {
|
|
18
20
|
grant: ClaustrumRequestedGrant;
|
|
@@ -62,6 +64,8 @@ export interface SetupPlugin {
|
|
|
62
64
|
name: string;
|
|
63
65
|
displayName?: string;
|
|
64
66
|
requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
|
|
67
|
+
/** Who reports access when grants were not sent with enrollment; defaults to 'setup'. */
|
|
68
|
+
grantFallback?: 'setup' | 'plugin';
|
|
65
69
|
paths: Parameters<typeof hostEnrollmentPaths>[0];
|
|
66
70
|
}>;
|
|
67
71
|
};
|