@cortexkit/common-auth 0.23.0 → 0.24.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.
@@ -1,4 +1,9 @@
1
1
  import { type ClaustrumClientOptions as ClaustrumEnrollmentClientOptions, type EnrollmentPollOutcome, type EnrollmentTokenFile, writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
2
+ /**
3
+ * The code a vault without the enrollment ceremony answers a proposal with.
4
+ * Setup reports it as "this vault cannot connect plugins" instead of waiting.
5
+ */
6
+ export declare const UNSUPPORTED_ENROLLMENT_CODE = "unknown_method";
2
7
  /**
3
8
  * Codes the vault's closed enrollment-refusal vocabulary marks permanent. The
4
9
  * client labels some module error frames transient/retry regardless, so the
@@ -10,12 +10,22 @@ const ENROLLMENT_SCHEMA = 1;
10
10
  const ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
11
11
  const ENROLLMENT_LOCK_TTL_MS = 30_000;
12
12
  const TOKEN_RE = /^[0-9a-f]{64}$/;
13
+ /**
14
+ * The code a vault without the enrollment ceremony answers a proposal with.
15
+ * Setup reports it as "this vault cannot connect plugins" instead of waiting.
16
+ */
17
+ export const UNSUPPORTED_ENROLLMENT_CODE = 'unknown_method';
13
18
  /**
14
19
  * Codes the vault's closed enrollment-refusal vocabulary marks permanent. The
15
20
  * client labels some module error frames transient/retry regardless, so the
16
21
  * producer's code takes precedence over the client's action for these.
17
22
  */
18
23
  export const TERMINAL_ENROLLMENT_CODES = new Set([
24
+ // The daemon's answer to an operation it does not implement: a vault built
25
+ // before the enrollment ceremony. It arrives as a transport Error frame with
26
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
27
+ // asking again can never succeed.
28
+ UNSUPPORTED_ENROLLMENT_CODE,
19
29
  'invalid_params',
20
30
  'pending_exists',
21
31
  'not_found',
@@ -638,6 +648,23 @@ export class ClaustrumEnrollmentManager {
638
648
  retryCode: refusal.code,
639
649
  };
640
650
  }
651
+ // A vault without the ceremony cannot hold a request for this
652
+ // proposal, now or from an earlier run (the state has no request
653
+ // id). So nothing is blocked and nothing is in progress: remove the
654
+ // pending state, still under the ceremony lock, so status reads as
655
+ // "not enrolled" and a reset or a later run starts afresh.
656
+ if (refusal.code === UNSUPPORTED_ENROLLMENT_CODE) {
657
+ await lock.assertOwned();
658
+ await unlink(this.#paths.statePath).catch((cause) => {
659
+ if (cause.code !== 'ENOENT')
660
+ throw cause;
661
+ });
662
+ return {
663
+ state: 'unavailable',
664
+ proposedName: state.proposedName,
665
+ code: refusal.code,
666
+ };
667
+ }
641
668
  return this.#block(state, refusal.code);
642
669
  }
643
670
  }
@@ -5,6 +5,8 @@ type Backend = typeof import('@cortexkit/private-files');
5
5
  type Kind = 'file' | 'directory';
6
6
  /** Tests inject a backend here; production always imports the private-files package. */
7
7
  export declare function setPrivateFilesBackendForTest(api?: Backend): void;
8
+ /** The fixed `reason` of a refusal because the Windows native addon did not load. */
9
+ export declare const PRIVATE_FILES_UNAVAILABLE_REASON = "native-addon-unavailable";
8
10
  export declare class PrivateFileError extends Error {
9
11
  readonly path: string;
10
12
  readonly stage: string;
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { lstat, readFile, rename, unlink } from 'node:fs/promises';
3
- import { dirname, resolve } from 'node:path';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
4
5
  export const windowsPrivateFiles = process.platform === 'win32';
5
6
  const migrationNotices = new Set();
6
7
  function ioCode(detail) {
@@ -20,8 +21,51 @@ let backend;
20
21
  export function setPrivateFilesBackendForTest(api) {
21
22
  backend = api ? Promise.resolve(api) : undefined;
22
23
  }
24
+ /** The fixed `reason` of a refusal because the Windows native addon did not load. */
25
+ export const PRIVATE_FILES_UNAVAILABLE_REASON = 'native-addon-unavailable';
26
+ function privateFilesUnavailable(cause) {
27
+ return Object.assign(new Error('Windows private-files native addon is unavailable', { cause }), {
28
+ code: 'ERR_PRIVATE_FILES_UNAVAILABLE',
29
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON,
30
+ });
31
+ }
32
+ function isUnavailable(api, error) {
33
+ return (error instanceof api.PrivateFilesUnavailableError ||
34
+ error?.code ===
35
+ 'ERR_PRIVATE_FILES_UNAVAILABLE');
36
+ }
37
+ /**
38
+ * Importing @cortexkit/private-files succeeds even when its Windows addon
39
+ * cannot load: the package loads the addon on first use, and some of its
40
+ * checks then report the failure as an ordinary refusal such as
41
+ * `unsupported-filesystem`. So prove the addon loads before handing the
42
+ * package out. Verifying a path that does not exist loads the addon first and
43
+ * then fails harmlessly; only the package's own "unavailable" error means the
44
+ * addon is missing.
45
+ */
46
+ async function assertNativeAddonLoads(api) {
47
+ try {
48
+ await api.verifyPrivatePath(join(tmpdir(), `.common-auth-private-files-probe-${randomUUID()}`), 'file');
49
+ }
50
+ catch (error) {
51
+ if (isUnavailable(api, error))
52
+ throw privateFilesUnavailable(error);
53
+ }
54
+ }
55
+ /**
56
+ * Load the package once per process. On Windows a failed import or addon load
57
+ * is kept, so every later private-file operation refuses at once with
58
+ * ERR_PRIVATE_FILES_UNAVAILABLE. There is no fallback to permission bits:
59
+ * they do not protect files on Windows.
60
+ */
23
61
  function loadBackend() {
24
- backend ??= import('@cortexkit/private-files');
62
+ backend ??= import('@cortexkit/private-files').then(async (api) => {
63
+ if (windowsPrivateFiles)
64
+ await assertNativeAddonLoads(api);
65
+ return api;
66
+ }, (cause) => {
67
+ throw windowsPrivateFiles ? privateFilesUnavailable(cause) : cause;
68
+ });
25
69
  return backend;
26
70
  }
27
71
  export class PrivateFileError extends Error {
@@ -38,7 +82,9 @@ export class PrivateFileError extends Error {
38
82
  orphanPath;
39
83
  constructor(path, stage, cause) {
40
84
  const detail = cause;
41
- super(`Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
85
+ super(detail?.code === 'ERR_PRIVATE_FILES_UNAVAILABLE'
86
+ ? `Private file refused at ${stage}: ${path} (${PRIVATE_FILES_UNAVAILABLE_REASON}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
87
+ : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
42
88
  this.path = path;
43
89
  this.stage = stage;
44
90
  this.name = 'PrivateFileError';
@@ -1,13 +1,34 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
2
  import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
3
+ /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
4
+ export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.";
5
+ /**
6
+ * The longest setup waits, in total, for the vault to create the enrollment
7
+ * request and for an operator to approve it. It matches the wait setup always
8
+ * had (300 one-second polls), but is now measured on the clock: a vault that
9
+ * answers each request slowly can no longer stretch it.
10
+ */
11
+ export declare const ENROLLMENT_WAIT_MS = 300000;
12
+ /** Why a host's enrollment ended without a token. */
13
+ export type HostNotEnrolledReason = 'connection-failed' | 'unsupported-vault' | 'request-not-created' | 'approval-pending' | 'refused' | 'invalid-request' | 'incomplete';
3
14
  /**
4
15
  * Thrown when the enrollment ended without writing the host's token: the vault
5
- * could not be reached, it refused the request, or approval never came before
6
- * setup stopped waiting. Setup can then report the host as not connected
7
- * without reading its files. The message is the same one a plain error would
8
- * carry, so the user sees no difference.
16
+ * could not be reached, it cannot enroll plugins, it refused the request, it
17
+ * never created one, approval never came before setup stopped waiting, or
18
+ * the enrollment failed in some other way (`incomplete`).
19
+ * Setup can then report the host as not connected without reading its files.
20
+ * The message is fixed text built only from vetted values, never from what
21
+ * the vault or client threw. `lastErrorCode` is the last enrollment error code
22
+ * setup saw, from the vault or from the client's transport (for example
23
+ * `transport_error`), for diagnostics; it carries no secret.
9
24
  */
10
25
  export declare class HostNotEnrolledError extends Error {
26
+ readonly reason: HostNotEnrolledReason;
27
+ readonly lastErrorCode?: string;
28
+ constructor(message: string, details: {
29
+ reason: HostNotEnrolledReason;
30
+ lastErrorCode?: string;
31
+ });
11
32
  }
12
33
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
13
34
  export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<void>;
@@ -1,17 +1,53 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
3
3
  import { printLine } from '../auth-menu/terminal.js';
4
- import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, } from '../claustrum/enrollment.js';
4
+ import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, UNSUPPORTED_ENROLLMENT_CODE, } from '../claustrum/enrollment.js';
5
5
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
6
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
7
+ /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
8
+ export const UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.';
9
+ /**
10
+ * The longest setup waits, in total, for the vault to create the enrollment
11
+ * request and for an operator to approve it. It matches the wait setup always
12
+ * had (300 one-second polls), but is now measured on the clock: a vault that
13
+ * answers each request slowly can no longer stretch it.
14
+ */
15
+ export const ENROLLMENT_WAIT_MS = 300_000;
16
+ /** The pause between polls while a created request waits for approval. */
17
+ const APPROVAL_POLL_MS = 1000;
18
+ /**
19
+ * Pauses between proposals the vault failed to accept for a reason worth
20
+ * retrying; the last value repeats until the overall wait runs out.
21
+ */
22
+ const PROPOSE_BACKOFF_MS = [1000, 2000, 4000, 8000, 16_000, 30_000];
23
+ /** Vault codes are short snake_case words; anything else is shown as `unknown`. */
24
+ function safeCode(code) {
25
+ return code && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : 'unknown';
26
+ }
7
27
  /**
8
28
  * Thrown when the enrollment ended without writing the host's token: the vault
9
- * could not be reached, it refused the request, or approval never came before
10
- * setup stopped waiting. Setup can then report the host as not connected
11
- * without reading its files. The message is the same one a plain error would
12
- * carry, so the user sees no difference.
29
+ * could not be reached, it cannot enroll plugins, it refused the request, it
30
+ * never created one, approval never came before setup stopped waiting, or
31
+ * the enrollment failed in some other way (`incomplete`).
32
+ * Setup can then report the host as not connected without reading its files.
33
+ * The message is fixed text built only from vetted values, never from what
34
+ * the vault or client threw. `lastErrorCode` is the last enrollment error code
35
+ * setup saw, from the vault or from the client's transport (for example
36
+ * `transport_error`), for diagnostics; it carries no secret.
13
37
  */
14
38
  export class HostNotEnrolledError extends Error {
39
+ reason;
40
+ lastErrorCode;
41
+ constructor(message, details) {
42
+ super(message);
43
+ this.name = 'HostNotEnrolledError';
44
+ this.reason = details.reason;
45
+ if (details.lastErrorCode !== undefined)
46
+ this.lastErrorCode = safeCode(details.lastErrorCode);
47
+ }
48
+ }
49
+ function approveCommand(requestId, name) {
50
+ return `ck auth enroll approve --request-id ${requestId} --name ${name}`;
15
51
  }
16
52
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
17
53
  export async function connectSetupHost(plugin, host, io, terminal, fence) {
@@ -22,59 +58,105 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
22
58
  connectionFile: plugin.vault.connectionFile,
23
59
  handshakeTimeoutMs: 2000,
24
60
  }).catch(() => {
25
- throw new HostNotEnrolledError('Claustrum connection failed; start ck and rerun setup.');
61
+ throw new HostNotEnrolledError('Claustrum connection failed; start ck and rerun setup.', { reason: 'connection-failed' });
26
62
  });
63
+ const now = io.now ?? (() => performance.now());
64
+ const wait = io.wait ?? delay;
27
65
  try {
28
66
  const manager = new ClaustrumEnrollmentManager({
29
67
  proposedName: name,
30
68
  paths,
31
- client: {
32
- enrollPropose: async (input) => {
33
- await fence();
34
- return client.enrollPropose(input);
35
- },
36
- enrollPoll: async (input) => {
37
- await fence();
38
- return client.enrollPoll(input);
39
- },
40
- },
69
+ // Each tick of the wait below checks the fence once, just before
70
+ // reconcile proposes or polls. Checking again inside every vault call
71
+ // doubled the process listings per tick, and on Windows each listing
72
+ // starts PowerShell.
73
+ client,
41
74
  writeTokenFile: async (path, file) => {
75
+ // Writing the token is what connects the host: check once more.
42
76
  await fence();
43
77
  await writeEnrollmentTokenFile(path, file);
44
78
  },
45
79
  });
80
+ printLine(terminal, `Asking the vault to connect ${name}…`);
81
+ const deadline = now() + ENROLLMENT_WAIT_MS;
46
82
  let printedRequest;
47
- for (let tick = 0; tick < 300; tick++) {
83
+ let lastCode;
84
+ let reportedCode;
85
+ let failedProposals = 0;
86
+ for (;;) {
48
87
  await fence();
49
88
  const status = await manager.reconcile();
50
89
  if (status.state === 'approved') {
51
90
  printLine(terminal, `Connected ${host} to Claustrum.`);
52
91
  return;
53
92
  }
93
+ if (status.state === 'unavailable' &&
94
+ status.code === UNSUPPORTED_ENROLLMENT_CODE)
95
+ throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
96
+ reason: 'unsupported-vault',
97
+ lastErrorCode: status.code,
98
+ });
54
99
  if (status.state !== 'pending' && status.state !== 'busy')
55
- throw new HostNotEnrolledError('Claustrum enrollment refused; inspect its status with ck before rerunning setup.');
56
- if (status.state === 'pending' &&
57
- status.requestId &&
58
- status.requestId !== printedRequest) {
59
- if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
60
- throw new HostNotEnrolledError('Invalid enrollment request id.');
61
- printedRequest = status.requestId;
62
- printLine(terminal, 'Waiting for approval. In another terminal, run:');
63
- printLine(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
64
- printLine(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
100
+ throw new HostNotEnrolledError('Claustrum enrollment refused; inspect its status with ck before rerunning setup.', {
101
+ reason: 'refused',
102
+ ...('code' in status && { lastErrorCode: status.code }),
103
+ });
104
+ let pause = APPROVAL_POLL_MS;
105
+ if (status.state === 'busy')
106
+ lastCode = 'busy';
107
+ else if (status.retryCode)
108
+ lastCode = status.retryCode;
109
+ if (status.state === 'pending' && status.requestId) {
110
+ failedProposals = 0;
111
+ if (status.requestId !== printedRequest) {
112
+ if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
113
+ throw new HostNotEnrolledError('Invalid enrollment request id.', {
114
+ reason: 'invalid-request',
115
+ });
116
+ printedRequest = status.requestId;
117
+ printLine(terminal, 'Waiting for approval. In another terminal, run:');
118
+ printLine(terminal, ` ${approveCommand(status.requestId, name)}`);
119
+ printLine(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
120
+ }
65
121
  }
66
- await (io.wait ?? delay)(1000);
122
+ else if (status.state === 'pending' && status.retryCode) {
123
+ // No request id came back. Back off instead of asking
124
+ // again every second, and say so once per distinct code.
125
+ pause =
126
+ PROPOSE_BACKOFF_MS[Math.min(failedProposals, PROPOSE_BACKOFF_MS.length - 1)] ?? APPROVAL_POLL_MS;
127
+ failedProposals++;
128
+ const code = safeCode(status.retryCode);
129
+ if (code !== reportedCode) {
130
+ reportedCode = code;
131
+ printLine(terminal, `The vault has not created the request yet (${code}); retrying.`);
132
+ }
133
+ }
134
+ const remaining = deadline - now();
135
+ if (remaining <= 0)
136
+ break;
137
+ await wait(Math.min(pause, remaining));
67
138
  }
68
- throw new HostNotEnrolledError('Claustrum approval is still pending; approve with ck and rerun setup.');
139
+ if (printedRequest)
140
+ throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
141
+ reason: 'approval-pending',
142
+ ...(lastCode !== undefined && { lastErrorCode: lastCode }),
143
+ });
144
+ const code = safeCode(lastCode);
145
+ throw new HostNotEnrolledError(`The vault never created the enrollment request (last error: ${code}). Check that ck is running, then rerun setup.`, { reason: 'request-not-created', lastErrorCode: code });
69
146
  }
70
147
  catch (error) {
71
148
  if (error instanceof ProcessFenceViolationError ||
72
- error instanceof ProcessInspectionError)
149
+ error instanceof ProcessInspectionError ||
150
+ // Built above from fixed text and vetted values only.
151
+ error instanceof HostNotEnrolledError)
73
152
  throw error;
74
- // Enrollment exceptions can carry request secrets or bearer tokens; never display them.
75
- if (error instanceof HostNotEnrolledError)
76
- throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
77
- throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
153
+ // Enrollment exceptions can carry request secrets or bearer tokens; never
154
+ // display them. Only a vetted error code goes into the diagnostics.
155
+ const code = error?.code;
156
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE, {
157
+ reason: 'incomplete',
158
+ ...(typeof code === 'string' && { lastErrorCode: code }),
159
+ });
78
160
  }
79
161
  finally {
80
162
  client.close();
@@ -1,6 +1,7 @@
1
1
  export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
2
  export { SetupCommandError, setupEnrollment } from './command-error.js';
3
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
4
+ export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, type HostNotEnrolledReason, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
4
5
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
5
6
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
6
7
  export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -1,5 +1,6 @@
1
1
  export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
2
  export { SetupCommandError, setupEnrollment } from './command-error.js';
3
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
4
+ export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
4
5
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
5
6
  export { planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
@@ -39,6 +39,13 @@ export declare function listSetupProcesses(runner?: CommandRunner, options?: {
39
39
  * a container this process can hold any small PID a fixture uses.
40
40
  */
41
41
  selfPid?: number;
42
+ /**
43
+ * Windows only: answer with one CIM query for the images a fence cares
44
+ * about (host programs, Node and Bun), returning image name, PID and
45
+ * command line together, instead of `tasklist` followed by a second CIM
46
+ * query. The result lists only those processes.
47
+ */
48
+ hostImagesOnly?: boolean;
42
49
  }): Promise<Array<{
43
50
  pid: number;
44
51
  command: string;
@@ -5,6 +5,18 @@ import { defaultCommandRunner } from './command-runner.js';
5
5
  const WINDOWS_CIM_TIMEOUT_MS = 45_000;
6
6
  const HOSTS = new Set(['opencode', 'litecode', 'opencode2', 'pi']);
7
7
  const RUNTIMES = new Set(['node', 'bun']);
8
+ /**
9
+ * The fence's one Windows query. It selects every image whose name starts
10
+ * with a host or runtime name, a superset of what `hostName` can recognize
11
+ * from an image (it strips only an extension), and returns image name, PID
12
+ * and command line from one snapshot. The answer always carries
13
+ * `complete: true`, so an empty or cut-off answer is never mistaken for an
14
+ * empty process list.
15
+ */
16
+ const WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES]
17
+ .map((name) => `Name LIKE '${name}%'`)
18
+ .join(' OR ');
19
+ const WINDOWS_FENCE_QUERY = `$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${WINDOWS_FENCE_FILTER}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`;
8
20
  const PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
9
21
  /** Splits a command line into arguments, keeping double-quoted ones whole. */
10
22
  function commandArguments(command) {
@@ -169,6 +181,45 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
169
181
  }
170
182
  };
171
183
  try {
184
+ if (windows && options.hostImagesOnly) {
185
+ const details = await inspect('CIM', 'powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
186
+ if (details.exitCode !== 0)
187
+ throw new ProcessInspectionError(inspection);
188
+ // An empty or truncated answer fails to parse or lacks `complete`, so a
189
+ // query that silently printed nothing is never read as "no hosts".
190
+ const value = JSON.parse(details.stdout);
191
+ if (!value ||
192
+ typeof value !== 'object' ||
193
+ !('complete' in value) ||
194
+ value.complete !== true ||
195
+ !('processes' in value))
196
+ throw new ProcessInspectionError(inspection);
197
+ const listed = value.processes;
198
+ const rows = listed === null ? [] : Array.isArray(listed) ? listed : [listed];
199
+ const processes = [];
200
+ for (const row of rows) {
201
+ if (!row ||
202
+ typeof row !== 'object' ||
203
+ !('Name' in row) ||
204
+ typeof row.Name !== 'string' ||
205
+ !('ProcessId' in row) ||
206
+ !Number.isSafeInteger(row.ProcessId) ||
207
+ row.ProcessId < 0 ||
208
+ !('CommandLine' in row))
209
+ throw new ProcessInspectionError(inspection);
210
+ const pid = row.ProcessId;
211
+ // As with tasklist, a host program is judged by its image name, and
212
+ // a Node or Bun process by the script on its command line. A runtime
213
+ // whose command line cannot be read cannot be cleared.
214
+ if (!/^(?:node|bun)\.exe$/i.test(row.Name))
215
+ processes.push({ pid, command: row.Name });
216
+ else if (typeof row.CommandLine === 'string')
217
+ processes.push({ pid, command: row.CommandLine });
218
+ else if (pid !== selfPid)
219
+ throw new ProcessInspectionError(inspection);
220
+ }
221
+ return processes;
222
+ }
172
223
  const result = await inspect(windows ? 'tasklist' : 'ps', windows ? 'tasklist.exe' : 'ps', windows ? ['/fo', 'csv', '/nh'] : ['-eo', 'pid,command']);
173
224
  if (result.exitCode !== 0)
174
225
  throw new ProcessInspectionError(inspection);
@@ -246,7 +297,11 @@ export function createProcessFence(runner = defaultCommandRunner, options = {})
246
297
  const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
247
298
  return {
248
299
  async listRunningHosts(env) {
249
- return (await listSetupProcesses(runner, { ...options, env })).filter(isHost);
300
+ return (await listSetupProcesses(runner, {
301
+ ...options,
302
+ env,
303
+ hostImagesOnly: true,
304
+ })).filter(isHost);
250
305
  },
251
306
  async previewRunningHosts(env) {
252
307
  const processes = await listSetupProcesses(runner, {
@@ -125,6 +125,11 @@ export interface SetupIO {
125
125
  handshakeTimeoutMs: number;
126
126
  }) => Promise<ClaustrumEnrollmentConnection>;
127
127
  wait?: (ms: number) => Promise<void>;
128
+ /**
129
+ * Monotonic milliseconds that bound the enrollment wait. Defaults to
130
+ * `performance.now`; tests pair it with `wait` to run a fake clock.
131
+ */
132
+ now?: () => number;
128
133
  }
129
134
  export interface HostDetection {
130
135
  installed: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.23.0",
3
+ "version": "0.24.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": {