@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
@@ -3,6 +3,7 @@ import { writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
3
3
  import { printLine } from '../auth-menu/terminal.js';
4
4
  import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, UNSUPPORTED_ENROLLMENT_CODE, } from '../claustrum/enrollment.js';
5
5
  import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
6
+ import { confirmEnrollmentAccess, enrollmentAccessLines, } from './enrollment-access.js';
6
7
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
7
8
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
8
9
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
@@ -54,7 +55,7 @@ function approveCommand(requestId, name) {
54
55
  export async function connectSetupHost(plugin, host, io, terminal, fence) {
55
56
  if (hasVaultHost())
56
57
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
57
- const { name, displayName, paths: input } = plugin.vault.hosts[host];
58
+ const { name, displayName, requestedGrants, grantFallback, paths: input, } = plugin.vault.hosts[host];
58
59
  const paths = hostEnrollmentPaths(input);
59
60
  await fence();
60
61
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
@@ -69,6 +70,7 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
69
70
  const manager = new ClaustrumEnrollmentManager({
70
71
  proposedName: name,
71
72
  displayName,
73
+ requestedGrants,
72
74
  paths,
73
75
  // Each tick of the wait below checks the fence once, just before
74
76
  // reconcile proposes or polls. Checking again inside every vault call
@@ -85,7 +87,11 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
85
87
  const initial = await manager.status();
86
88
  if (initial.state === 'approved') {
87
89
  printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
88
- return;
90
+ const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
91
+ if (access)
92
+ for (const line of enrollmentAccessLines(access, grantFallback))
93
+ printLine(terminal, line);
94
+ return access;
89
95
  }
90
96
  printLine(terminal, `Asking the vault to connect ${name}…`);
91
97
  const deadline = now() + ENROLLMENT_WAIT_MS;
@@ -97,7 +103,11 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
97
103
  const status = await manager.reconcile();
98
104
  if (status.state === 'approved') {
99
105
  printLine(terminal, `Connected ${host} to Claustrum.`);
100
- return;
106
+ const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
107
+ if (access)
108
+ for (const line of enrollmentAccessLines(access, grantFallback))
109
+ printLine(terminal, line);
110
+ return access;
101
111
  }
102
112
  if (status.state === 'unavailable' &&
103
113
  status.code === UNSUPPORTED_ENROLLMENT_CODE)
@@ -0,0 +1,7 @@
1
+ import type { ClaustrumEnrollmentConnection, ClaustrumEnrollmentStatus, ClaustrumRequestedGrant } from '../claustrum/enrollment.js';
2
+ import type { SetupEnrollmentAccess } from './types.js';
3
+ /** Check access on the enrollment connection, after the token has reached disk. */
4
+ export declare function confirmEnrollmentAccess(client: Pick<ClaustrumEnrollmentConnection, 'listScoped'>, status: Extract<ClaustrumEnrollmentStatus, {
5
+ state: 'approved';
6
+ }>, tokenPath: string, configuredGrants: ReadonlyArray<ClaustrumRequestedGrant> | undefined): Promise<SetupEnrollmentAccess | undefined>;
7
+ export declare function enrollmentAccessLines(access: SetupEnrollmentAccess, grantFallback?: 'setup' | 'plugin'): string[];
@@ -0,0 +1,86 @@
1
+ import { readClaustrumEnrollmentToken } from '../claustrum/enrollment.js';
2
+ function shellArgument(value) {
3
+ if (/^[a-zA-Z0-9_:@./-]+$/.test(value))
4
+ return value;
5
+ return process.platform === 'win32'
6
+ ? `'${value.replaceAll("'", "''")}'`
7
+ : `'${value.replaceAll("'", "'\\''")}'`;
8
+ }
9
+ /** Check access on the enrollment connection, after the token has reached disk. */
10
+ export async function confirmEnrollmentAccess(client, status, tokenPath, configuredGrants) {
11
+ const requestedGrants = status.requestedGrants ?? configuredGrants;
12
+ if (!requestedGrants)
13
+ return undefined;
14
+ const grants = requestedGrants.map((grant) => ({
15
+ grant,
16
+ ...(status.approvedName !== undefined && {
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
+ }),
19
+ }));
20
+ const access = {
21
+ grants,
22
+ ...(status.requestedGrantsStatus !== undefined && {
23
+ requestedGrantsStatus: status.requestedGrantsStatus,
24
+ }),
25
+ };
26
+ if (status.requestedGrantsStatus === 'dropped')
27
+ return { ...access, state: 'older-vault' };
28
+ try {
29
+ if (!client.listScoped)
30
+ return { ...access, state: 'unconfirmed' };
31
+ const { token } = await readClaustrumEnrollmentToken(tokenPath);
32
+ const inventory = await client.listScoped(token);
33
+ const confirmed = grants.map((entry) => ({
34
+ ...entry,
35
+ reachableLogins: inventory.rows.filter((row) => row.operations.includes(entry.grant.operation) &&
36
+ (entry.grant.selector.exact !== undefined
37
+ ? row.id === entry.grant.selector.exact
38
+ : row.categories.includes(entry.grant.selector.category))).length,
39
+ }));
40
+ return {
41
+ ...access,
42
+ state: confirmed.every((entry) => entry.reachableLogins > 0)
43
+ ? 'reachable'
44
+ : confirmed.some((entry) => entry.reachableLogins > 0)
45
+ ? 'partial'
46
+ : 'no-logins',
47
+ grants: confirmed.map((entry) => {
48
+ if (entry.reachableLogins === 0)
49
+ return entry;
50
+ const { grantCommand: _, ...reachable } = entry;
51
+ return reachable;
52
+ }),
53
+ };
54
+ }
55
+ catch {
56
+ // A listing failure cannot undo approval, and its error may contain secrets.
57
+ return { ...access, state: 'unconfirmed' };
58
+ }
59
+ }
60
+ export function enrollmentAccessLines(access, grantFallback = 'setup') {
61
+ if (grantFallback === 'plugin' && access.requestedGrantsStatus !== 'sent')
62
+ return [];
63
+ const lines = [];
64
+ const remedy = access.grants.some((entry) => entry.grantCommand)
65
+ ? 'run:'
66
+ : 'check ck auth status for the approved name before granting access.';
67
+ if (access.state === 'older-vault')
68
+ lines.push(`Approved. This vault is too old to grant access with the approval; ${remedy}`);
69
+ else if (access.state === 'no-logins')
70
+ lines.push(`Approved, but no logins are reachable yet; ${remedy}`);
71
+ else if (access.state === 'partial')
72
+ lines.push(`Approved, but some requested access has no reachable logins yet; ${remedy}`);
73
+ else if (access.state === 'unconfirmed')
74
+ lines.push(`Approved, but access could not be confirmed; ${access.grants.some((entry) => entry.grantCommand) ? 'check ck auth status or run:' : remedy}`);
75
+ for (const { grant, reachableLogins, grantCommand } of access.grants) {
76
+ if (reachableLogins !== undefined && reachableLogins > 0) {
77
+ const target = grant.selector.exact === undefined
78
+ ? `the vault's ${JSON.stringify(grant.selector.category)} accounts`
79
+ : `credential ${JSON.stringify(grant.selector.exact)}`;
80
+ lines.push(`Confirmed ${grant.operation} access to ${target} (${reachableLogins} reachable ${reachableLogins === 1 ? 'login' : 'logins'}).`);
81
+ }
82
+ if (grantCommand)
83
+ lines.push(` ${grantCommand}`);
84
+ }
85
+ return lines;
86
+ }
@@ -5,4 +5,4 @@ export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, type HostNotEnrolledReason, U
5
5
  export { setupUsage } from './flags.js';
6
6
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
7
7
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
8
- export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
8
+ export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentAccess, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -1,5 +1,5 @@
1
1
  import type { MenuTerminal } from '../auth-menu/terminal.js';
2
- import type { ClaustrumEnrollmentConnection, hostEnrollmentPaths } from '../claustrum/index.js';
2
+ import type { ClaustrumEnrollmentConnection, ClaustrumRequestedGrant, hostEnrollmentPaths } from '../claustrum/index.js';
3
3
  export type SetupHost = 'opencode' | 'pi';
4
4
  export type OpenCodeGeneration = '1' | '2' | 'both';
5
5
  export type SetupEnvironment = Record<string, string | undefined>;
@@ -11,9 +11,21 @@ export type SetupEnvironment = Record<string, string | undefined>;
11
11
  * flight and the host's token file could not settle it.
12
12
  */
13
13
  export type SetupEnrollmentOutcome = 'enrolled' | 'not-enrolled' | 'unknown';
14
+ export interface SetupEnrollmentAccess {
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';
18
+ /** One result per requested grant, in proposal order. No count means unknown. */
19
+ grants: readonly {
20
+ grant: ClaustrumRequestedGrant;
21
+ reachableLogins?: number;
22
+ grantCommand?: string;
23
+ }[];
24
+ }
14
25
  export interface SetupHostEnrollment {
15
26
  host: SetupHost;
16
27
  outcome: SetupEnrollmentOutcome;
28
+ access?: SetupEnrollmentAccess;
17
29
  }
18
30
  /**
19
31
  * What setup decided before calling a plugin callback. The OpenCode generation
@@ -51,6 +63,9 @@ export interface SetupPlugin {
51
63
  hosts: Record<SetupHost, {
52
64
  name: string;
53
65
  displayName?: string;
66
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
67
+ /** Who reports access when grants were not sent with enrollment; defaults to 'setup'. */
68
+ grantFallback?: 'setup' | 'plugin';
54
69
  paths: Parameters<typeof hostEnrollmentPaths>[0];
55
70
  }>;
56
71
  };
@@ -1,6 +1,6 @@
1
1
  import { type Stats, watch } from 'node:fs';
2
2
  import { PrivateFileError } from '../fs/private-files.js';
3
- type Metadata = Pick<Stats, 'mtimeMs' | 'size' | 'ino' | 'dev'>;
3
+ type Metadata = Pick<Stats, 'mtimeMs' | 'size' | 'ino' | 'dev'> & Partial<Pick<Stats, 'ctimeMs'>>;
4
4
  export interface TuiPreferencesWatchOptions {
5
5
  /** Receives PrivateFileError instances for Windows access failures, never file contents. */
6
6
  onError?: (error: PrivateFileError) => void;
@@ -22,4 +22,6 @@ export interface TuiPreferencesWatchOptions {
22
22
  * disposable. The last unsubscribe stops both the native watcher and the poll.
23
23
  */
24
24
  export declare function watchTuiPreferences(file: string, onChange: () => void, options?: TuiPreferencesWatchOptions): () => void;
25
+ /** @internal Settings use ordinary reads and observe removal of the user path. */
26
+ export declare function watchSettings(file: string, onChange: () => void, options?: TuiPreferencesWatchOptions): () => void;
25
27
  export {};
@@ -18,8 +18,11 @@ function canonicalPath(file) {
18
18
  return parent === path ? path : join(canonicalPath(parent), basename(path));
19
19
  }
20
20
  }
21
- function identity(info) {
22
- return info && `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
21
+ function identity(info, settings) {
22
+ if (!info)
23
+ return null;
24
+ const value = `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
25
+ return settings ? `${value}:${info.ctimeMs}` : value;
23
26
  }
24
27
  /**
25
28
  * Share one directory watcher and metadata poll per canonical path, including
@@ -30,16 +33,25 @@ function identity(info) {
30
33
  * disposable. The last unsubscribe stops both the native watcher and the poll.
31
34
  */
32
35
  export function watchTuiPreferences(file, onChange, options = {}) {
36
+ return watchFile(file, onChange, options, false);
37
+ }
38
+ /** @internal Settings use ordinary reads and observe removal of the user path. */
39
+ export function watchSettings(file, onChange, options = {}) {
40
+ return watchFile(file, onChange, options, true);
41
+ }
42
+ function watchFile(file, onChange, options, settings) {
33
43
  const globals = globalThis;
34
- const key = Symbol.for('cortexkit.common-auth.tui-prefs.watchers.v1');
44
+ const key = Symbol.for(settings
45
+ ? 'cortexkit.common-auth.settings.watchers.v1'
46
+ : 'cortexkit.common-auth.tui-prefs.watchers.v1');
35
47
  const registry = globals[key] ?? new Map();
36
48
  globals[key] = registry;
37
- const path = canonicalPath(file);
49
+ const path = settings ? resolve(file) : canonicalPath(file);
38
50
  const shared = registry.get(path);
39
51
  if (shared)
40
52
  return shared.subscribe(onChange);
41
53
  const name = basename(path);
42
- const read = windowsPrivateFiles
54
+ const read = windowsPrivateFiles && !settings
43
55
  ? (file) => readPrivateText(file)
44
56
  : (options.fs?.readFile ?? ((file) => readFile(file, 'utf8')));
45
57
  const probe = options.fs?.stat ?? stat;
@@ -50,9 +62,9 @@ export function watchTuiPreferences(file, onChange, options = {}) {
50
62
  // Seed synchronously so an immediate write cannot be absorbed as the baseline.
51
63
  // The metadata is recorded only together with contents that were read, as in
52
64
  // the probe below: if the first read fails, the probe keeps trying.
53
- if (!windowsPrivateFiles)
65
+ if (settings || !windowsPrivateFiles)
54
66
  try {
55
- const metadata = identity((options.fs?.statSync ?? statSync)(path));
67
+ const metadata = identity((options.fs?.statSync ?? statSync)(path), settings);
56
68
  lastSeen = (options.fs?.readFileSync ?? ((file) => readFileSync(file, 'utf8')))(path);
57
69
  lastMetadata = metadata;
58
70
  }
@@ -61,19 +73,39 @@ export function watchTuiPreferences(file, onChange, options = {}) {
61
73
  }
62
74
  let disposed = false;
63
75
  const subscribers = new Set();
76
+ const notifySubscribers = () => {
77
+ for (const subscriber of [...subscribers]) {
78
+ if (!subscribers.has(subscriber))
79
+ continue;
80
+ try {
81
+ subscriber.notify();
82
+ }
83
+ catch {
84
+ // A broken subscriber must not prevent the others from observing a change.
85
+ }
86
+ }
87
+ };
64
88
  let checking = Promise.resolve();
65
89
  const checkForChange = (native) => {
66
90
  // Serialize native and poll checks so an older read cannot roll back state.
67
91
  checking = checking.then(async () => {
68
92
  if (disposed)
69
93
  return;
70
- const metadata = identity(await probe(path).catch(() => null));
94
+ const metadata = identity(await probe(path).catch(() => null), settings);
95
+ if (disposed)
96
+ return;
71
97
  if (!native && metadata === lastMetadata)
72
98
  return;
73
99
  // A missing file has nothing to read; remember that so the probe stays
74
100
  // quiet until it reappears.
75
101
  if (metadata === null) {
102
+ const disappeared = lastMetadata !== null;
76
103
  lastMetadata = null;
104
+ if (settings && disappeared) {
105
+ // Dropping the bytes makes recreation observable even with the old text.
106
+ lastSeen = null;
107
+ notifySubscribers();
108
+ }
77
109
  return;
78
110
  }
79
111
  const text = await read(path).catch((error) => {
@@ -96,16 +128,7 @@ export function watchTuiPreferences(file, onChange, options = {}) {
96
128
  if (text === lastSeen)
97
129
  return;
98
130
  lastSeen = text;
99
- for (const subscriber of [...subscribers]) {
100
- if (!subscribers.has(subscriber))
101
- continue;
102
- try {
103
- subscriber.notify();
104
- }
105
- catch {
106
- // A broken subscriber must not prevent the others from observing a change.
107
- }
108
- }
131
+ notifySubscribers();
109
132
  });
110
133
  return checking;
111
134
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.43.0",
3
+ "version": "0.45.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -48,6 +48,10 @@
48
48
  "types": "./dist/tui-prefs/index.d.ts",
49
49
  "import": "./dist/tui-prefs/index.js"
50
50
  },
51
+ "./settings": {
52
+ "types": "./dist/settings/index.d.ts",
53
+ "import": "./dist/settings/index.js"
54
+ },
51
55
  "./tui-build": {
52
56
  "types": "./dist/tui-build/index.d.ts",
53
57
  "import": "./dist/tui-build/index.js"
@@ -169,7 +173,7 @@
169
173
  },
170
174
  "devDependencies": {
171
175
  "@biomejs/biome": "2.5.14",
172
- "@cortexkit/claustrum-client": "^0.16.0",
176
+ "@cortexkit/claustrum-client": "^0.18.0",
173
177
  "@cortexkit/opencode-sidebar": "0.1.0",
174
178
  "@cortexkit/subc-client": "0.24.0",
175
179
  "@earendil-works/pi-coding-agent": "1.0.4",