@cortexkit/common-auth 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/claustrum/enrollment.d.ts +25 -4
  2. package/dist/claustrum/enrollment.js +81 -4
  3. package/dist/claustrum/index.d.ts +1 -1
  4. package/dist/claustrum/index.js +1 -1
  5. package/dist/commands/builtins.d.ts +20 -1
  6. package/dist/commands/builtins.js +28 -12
  7. package/dist/commands/index.d.ts +1 -1
  8. package/dist/commands/menu.d.ts +6 -1
  9. package/dist/commands/menu.js +1 -0
  10. package/dist/fs/file-read-cache.d.ts +3 -0
  11. package/dist/fs/file-read-cache.js +9 -5
  12. package/dist/fs/refresh-file-lock.d.ts +11 -0
  13. package/dist/fs/refresh-file-lock.js +146 -2
  14. package/dist/fs/with-lock.d.ts +2 -0
  15. package/dist/fs/with-lock.js +1 -1
  16. package/dist/settings/define.d.ts +35 -0
  17. package/dist/settings/define.js +52 -0
  18. package/dist/settings/descriptors.d.ts +97 -0
  19. package/dist/settings/descriptors.js +81 -0
  20. package/dist/settings/edit.d.ts +24 -0
  21. package/dist/settings/edit.js +229 -0
  22. package/dist/settings/fs.d.ts +6 -0
  23. package/dist/settings/fs.js +19 -0
  24. package/dist/settings/handle.d.ts +30 -0
  25. package/dist/settings/handle.js +228 -0
  26. package/dist/settings/index.d.ts +10 -0
  27. package/dist/settings/index.js +7 -0
  28. package/dist/settings/lock-errors.d.ts +2 -0
  29. package/dist/settings/lock-errors.js +15 -0
  30. package/dist/settings/move.d.ts +76 -0
  31. package/dist/settings/move.js +351 -0
  32. package/dist/settings/parse.d.ts +24 -0
  33. package/dist/settings/parse.js +65 -0
  34. package/dist/settings/paths.d.ts +12 -0
  35. package/dist/settings/paths.js +48 -0
  36. package/dist/settings/refusal.d.ts +7 -0
  37. package/dist/settings/refusal.js +15 -0
  38. package/dist/settings/resolve.d.ts +15 -0
  39. package/dist/settings/resolve.js +51 -0
  40. package/dist/settings/schema.d.ts +29 -0
  41. package/dist/settings/schema.js +81 -0
  42. package/dist/settings/snapshot.d.ts +24 -0
  43. package/dist/settings/snapshot.js +150 -0
  44. package/dist/settings/update.d.ts +6 -0
  45. package/dist/settings/update.js +139 -0
  46. package/dist/settings/write.d.ts +26 -0
  47. package/dist/settings/write.js +88 -0
  48. package/dist/setup/command-error.d.ts +1 -1
  49. package/dist/setup/command-error.js +4 -2
  50. package/dist/setup/command.js +23 -6
  51. package/dist/setup/enroll.d.ts +2 -2
  52. package/dist/setup/enroll.js +13 -3
  53. package/dist/setup/enrollment-access.d.ts +7 -0
  54. package/dist/setup/enrollment-access.js +86 -0
  55. package/dist/setup/index.d.ts +1 -1
  56. package/dist/setup/types.d.ts +16 -1
  57. package/dist/tui-prefs/watcher.d.ts +3 -1
  58. package/dist/tui-prefs/watcher.js +41 -18
  59. package/package.json +6 -2
@@ -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, }: SetupHostEnrollment): string;
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
@@ -1,5 +1,6 @@
1
1
  import { redact } from '../logger/redact.js';
2
2
  import { STDERR_TAIL_MAX_BYTES } from './command-runner.js';
3
+ import { enrollmentAccessLines } from './enrollment-access.js';
3
4
  const PI_INSTALL_ERROR_MESSAGE = 'Pi install failed; run pi install after checking your npm connection.';
4
5
  function utf8Tail(value) {
5
6
  const bytes = Buffer.from(value, 'utf8');
@@ -47,8 +48,9 @@ const OUTCOME_TEXT = {
47
48
  unknown: 'unknown, check with ck auth status',
48
49
  };
49
50
  /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
50
- export function setupEnrollmentLine({ host, outcome, }) {
51
- return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
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')}` : ''}`;
52
54
  }
53
55
  // Outcomes recorded against the value a failed `runSetup` threw. A WeakMap
54
56
  // keeps the thrown value itself untouched: setup never reads, rewrites or
@@ -1,11 +1,12 @@
1
1
  import { select } from '../auth-menu/select.js';
2
2
  import { isInteractive, printLine, processTerminal, } from '../auth-menu/terminal.js';
3
- import { hostEnrollmentPaths, vaultAuthority } from '../claustrum/enrollment.js';
3
+ import { hostEnrollmentPaths, readClaustrumEnrollmentStatus, validEnrollmentRequestedGrants, vaultAuthority, } from '../claustrum/enrollment.js';
4
4
  import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
5
5
  import { recordSetupEnrollment, setupEnrollmentLine } from './command-error.js';
6
6
  import { defaultCommandRunner } from './command-runner.js';
7
7
  import { detectHosts } from './detect.js';
8
8
  import { connectSetupHost, HostNotEnrolledError } from './enroll.js';
9
+ import { confirmEnrollmentAccess } from './enrollment-access.js';
9
10
  import { parseSetupFlags, UNAVAILABLE_HOST_MESSAGE } from './flags.js';
10
11
  import { setupPaths } from './paths.js';
11
12
  import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
@@ -22,6 +23,13 @@ function validatePlugin(plugin) {
22
23
  for (const host of Object.values(plugin.vault.hosts)) {
23
24
  if (!/^[a-z0-9][a-z0-9-]*$/.test(host.name))
24
25
  throw new Error('Setup requires lowercase vault names containing only letters, digits and dashes.');
26
+ if (host.requestedGrants !== undefined &&
27
+ !validEnrollmentRequestedGrants(host.requestedGrants))
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');
25
33
  }
26
34
  }
27
35
  /**
@@ -31,10 +39,11 @@ function validatePlugin(plugin) {
31
39
  * authority once with `vaultAuthority`; if that read fails it stays
32
40
  * `unknown`.
33
41
  */
34
- async function enrollmentReport(plugin, hosts, recorded) {
42
+ async function enrollmentReport(plugin, hosts, recorded, recordedAccess) {
35
43
  const report = [];
36
44
  for (const host of hosts) {
37
45
  let outcome = recorded.get(host) ?? 'not-enrolled';
46
+ let access = recordedAccess.get(host);
38
47
  if (outcome === 'unknown') {
39
48
  const { name, paths } = plugin.vault.hosts[host];
40
49
  const authority = await vaultAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
@@ -42,8 +51,13 @@ async function enrollmentReport(plugin, hosts, recorded) {
42
51
  outcome = 'enrolled';
43
52
  else if (authority === 'local')
44
53
  outcome = 'not-enrolled';
54
+ if (outcome === 'enrolled') {
55
+ const status = await readClaustrumEnrollmentStatus(hostEnrollmentPaths(paths), name).catch(() => undefined);
56
+ if (status?.state === 'approved')
57
+ access = await confirmEnrollmentAccess({}, status, hostEnrollmentPaths(paths).tokenPath, plugin.vault.hosts[host].requestedGrants);
58
+ }
45
59
  }
46
- report.push({ host, outcome });
60
+ report.push({ host, outcome, ...(access && { access }) });
47
61
  }
48
62
  return report;
49
63
  }
@@ -207,6 +221,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
207
221
  // Each host's vault enrollment as it happens. A host the operator approved
208
222
  // stays enrolled if a later step fails, so a failure reports this record.
209
223
  const enrollment = new Map();
224
+ const enrollmentAccess = new Map();
210
225
  try {
211
226
  for (const host of hosts) {
212
227
  await stopped();
@@ -215,7 +230,9 @@ export async function runSetup(plugin, argv = [], io = {}) {
215
230
  if (useVault) {
216
231
  enrollment.set(host, 'unknown');
217
232
  try {
218
- await connectSetupHost(plugin, host, io, terminal, stopped);
233
+ const access = await connectSetupHost(plugin, host, io, terminal, stopped);
234
+ if (access)
235
+ enrollmentAccess.set(host, access);
219
236
  }
220
237
  catch (error) {
221
238
  if (error instanceof HostNotEnrolledError)
@@ -248,10 +265,10 @@ export async function runSetup(plugin, argv = [], io = {}) {
248
265
  // then rethrow the original value untouched. Reporting must never
249
266
  // replace the failure, so its own errors are ignored.
250
267
  try {
251
- const report = await enrollmentReport(plugin, hosts, enrollment);
268
+ const report = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
252
269
  recordSetupEnrollment(error, report);
253
270
  for (const entry of report)
254
- printLine(terminal, setupEnrollmentLine(entry));
271
+ printLine(terminal, setupEnrollmentLine(entry, plugin.vault.hosts[entry.host].grantFallback));
255
272
  }
256
273
  catch { }
257
274
  throw error;
@@ -1,5 +1,5 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
- import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
2
+ import type { SetupEnrollmentAccess, SetupHost, SetupIO, SetupPlugin } from './types.js';
3
3
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
4
4
  export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read \"Upgrading from v0.1.3\" in its release notes first), or run setup without --claustrum to use local accounts.";
5
5
  /**
@@ -31,4 +31,4 @@ export declare class HostNotEnrolledError extends Error {
31
31
  });
32
32
  }
33
33
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
34
- export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<void>;
34
+ export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<SetupEnrollmentAccess | undefined>;