@cortexkit/common-auth 0.22.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.
- package/dist/claustrum/consumer.d.ts +3 -1
- package/dist/claustrum/consumer.js +25 -21
- package/dist/claustrum/enrollment.d.ts +5 -0
- package/dist/claustrum/enrollment.js +27 -0
- package/dist/claustrum/index.d.ts +1 -0
- package/dist/claustrum/index.js +1 -0
- package/dist/claustrum/quota-writer.d.ts +18 -0
- package/dist/claustrum/quota-writer.js +253 -0
- package/dist/claustrum/roster.d.ts +18 -2
- package/dist/claustrum/roster.js +100 -43
- package/dist/fs/private-files.d.ts +2 -0
- package/dist/fs/private-files.js +49 -3
- package/dist/fs/with-lock.d.ts +1 -0
- package/dist/fs/with-lock.js +2 -0
- package/dist/quota/format.d.ts +19 -0
- package/dist/quota/format.js +50 -5
- package/dist/quota/index.d.ts +3 -3
- package/dist/quota/index.js +2 -2
- package/dist/quota/map.d.ts +24 -1
- package/dist/quota/map.js +31 -6
- package/dist/quota/merge.d.ts +6 -1
- package/dist/quota/merge.js +17 -3
- package/dist/quota/projection.d.ts +3 -1
- package/dist/quota/projection.js +3 -1
- package/dist/setup/enroll.d.ts +25 -4
- package/dist/setup/enroll.js +116 -34
- package/dist/setup/index.d.ts +1 -0
- package/dist/setup/index.js +1 -0
- package/dist/setup/process-fence.d.ts +14 -0
- package/dist/setup/process-fence.js +61 -4
- package/dist/setup/types.d.ts +5 -0
- package/package.json +1 -1
package/dist/quota/merge.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// no entry gets an absence record. A pair outside the coverage is never
|
|
12
12
|
// touched, so a header-shaped partial observation (which covers only what it
|
|
13
13
|
// carries) cannot erase a family limit or the budget.
|
|
14
|
-
import { ALL_SCOPE, decodeQuotaMap, entryTime, isQuotaCounters, limitKey, } from './map.js';
|
|
14
|
+
import { ALL_SCOPE, decodeQuotaMap, entryTime, isQuotaCounters, isQuotaCredits, limitKey, } from './map.js';
|
|
15
15
|
/** Thrown by `mergeQuotaObservation` when either argument is malformed. */
|
|
16
16
|
export class QuotaCodecError extends TypeError {
|
|
17
17
|
constructor(message) {
|
|
@@ -84,7 +84,8 @@ export function isQuotaObservation(value) {
|
|
|
84
84
|
if (!coverage.every(isObservedPair))
|
|
85
85
|
return false;
|
|
86
86
|
return ((value.budget === undefined || isObservedBudget(value.budget)) &&
|
|
87
|
-
(value.counters === undefined || isQuotaCounters(value.counters))
|
|
87
|
+
(value.counters === undefined || isQuotaCounters(value.counters)) &&
|
|
88
|
+
(value.credits === undefined || isQuotaCredits(value.credits)));
|
|
88
89
|
}
|
|
89
90
|
function compareEntries(left, right) {
|
|
90
91
|
if (left.scope !== right.scope)
|
|
@@ -110,6 +111,17 @@ function mergeCounters(stored, observed) {
|
|
|
110
111
|
}
|
|
111
112
|
return counters.size === 0 ? undefined : Object.fromEntries(counters);
|
|
112
113
|
}
|
|
114
|
+
// Credits merge like a single counter: the newer record wins, an equal time
|
|
115
|
+
// applies (the observation applied last wins), and an observation without
|
|
116
|
+
// credits leaves the stored record alone.
|
|
117
|
+
function mergeCredits(stored, observed) {
|
|
118
|
+
if (observed === undefined)
|
|
119
|
+
return stored;
|
|
120
|
+
if (stored !== undefined && observed.checkedAt < stored.checkedAt) {
|
|
121
|
+
return stored;
|
|
122
|
+
}
|
|
123
|
+
return { ...observed };
|
|
124
|
+
}
|
|
113
125
|
/**
|
|
114
126
|
* Applies `observation` to `stored` (undefined for a row with no map yet) and
|
|
115
127
|
* returns the new map. Pure: neither argument is modified. Throws
|
|
@@ -166,13 +178,15 @@ export function mergeQuotaObservation(stored, observation) {
|
|
|
166
178
|
: { scope, label: pair.label, kind: 'retired', retiredAt: at });
|
|
167
179
|
}
|
|
168
180
|
// Keys this module does not recognise are carried over untouched.
|
|
169
|
-
const { limits: _limits, budget: _budget, counters: _counters, ...unknownKeys } = base;
|
|
181
|
+
const { limits: _limits, budget: _budget, counters: _counters, credits: _credits, ...unknownKeys } = base;
|
|
170
182
|
const budget = mergeBudget(base.budget, observation.budget, at);
|
|
171
183
|
const counters = mergeCounters(base.counters, observation.counters);
|
|
184
|
+
const credits = mergeCredits(base.credits, observation.credits);
|
|
172
185
|
return {
|
|
173
186
|
...unknownKeys,
|
|
174
187
|
limits: [...entries.values()].sort(compareEntries),
|
|
175
188
|
...(budget === undefined ? {} : { budget }),
|
|
176
189
|
...(counters === undefined ? {} : { counters }),
|
|
190
|
+
...(credits === undefined ? {} : { credits }),
|
|
177
191
|
};
|
|
178
192
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type QuotaCounter, type QuotaMap } from './map.js';
|
|
1
|
+
import { type QuotaCounter, type QuotaCredits, type QuotaMap } from './map.js';
|
|
2
2
|
export interface ProjectedLimit {
|
|
3
3
|
scope: string;
|
|
4
4
|
label: string;
|
|
@@ -40,6 +40,8 @@ export interface ProjectedQuota {
|
|
|
40
40
|
/** Present only when the stored budget is a reading, not cleared. */
|
|
41
41
|
budget?: ProjectedBudget;
|
|
42
42
|
counters?: Record<string, QuotaCounter>;
|
|
43
|
+
/** The stored prepaid credits, unchanged in every scope. */
|
|
44
|
+
credits?: QuotaCredits;
|
|
43
45
|
/**
|
|
44
46
|
* The named groups the windows belong to, in the order the plugin lists
|
|
45
47
|
* them. Set only by a plugin whose windows all belong to such groups; the
|
package/dist/quota/projection.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// scope, orders the result the way the primitives expect, and carries each
|
|
7
7
|
// entry's (scope, label) so a decision names the limit it judged rather than
|
|
8
8
|
// the position it occupied.
|
|
9
|
-
import { ALL_SCOPE, readQuotaCounters, } from './map.js';
|
|
9
|
+
import { ALL_SCOPE, isQuotaCredits, readQuotaCounters, } from './map.js';
|
|
10
10
|
function project(entry) {
|
|
11
11
|
if (entry.kind === 'retired') {
|
|
12
12
|
return {
|
|
@@ -95,12 +95,14 @@ export function projectQuota(map, scope = ALL_SCOPE) {
|
|
|
95
95
|
: undefined;
|
|
96
96
|
const budget = map?.budget?.kind === 'reading' ? projectBudget(map.budget) : undefined;
|
|
97
97
|
const counters = readQuotaCounters(map?.counters);
|
|
98
|
+
const credits = isQuotaCredits(map?.credits) ? map.credits : undefined;
|
|
98
99
|
return {
|
|
99
100
|
scope,
|
|
100
101
|
limits,
|
|
101
102
|
...(checkedAt === undefined ? {} : { checkedAt }),
|
|
102
103
|
...(budget === undefined ? {} : { budget }),
|
|
103
104
|
...(counters === undefined ? {} : { counters }),
|
|
105
|
+
...(credits === undefined ? {} : { credits }),
|
|
104
106
|
};
|
|
105
107
|
}
|
|
106
108
|
/**
|
package/dist/setup/enroll.d.ts
CHANGED
|
@@ -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
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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>;
|
package/dist/setup/enroll.js
CHANGED
|
@@ -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
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
throw new
|
|
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();
|
package/dist/setup/index.d.ts
CHANGED
|
@@ -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';
|
package/dist/setup/index.js
CHANGED
|
@@ -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';
|
|
@@ -33,11 +33,25 @@ export declare function listSetupProcesses(runner?: CommandRunner, options?: {
|
|
|
33
33
|
onStep?: (details: ProcessInspectionStep) => void;
|
|
34
34
|
/** False skips the Windows PowerShell query for Node and Bun command lines. */
|
|
35
35
|
inspectRuntimes?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* The process to leave out, the running setup itself. Defaults to
|
|
38
|
+
* `process.pid`; tests pass a value no listed process can have, because in
|
|
39
|
+
* a container this process can hold any small PID a fixture uses.
|
|
40
|
+
*/
|
|
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;
|
|
36
49
|
}): Promise<Array<{
|
|
37
50
|
pid: number;
|
|
38
51
|
command: string;
|
|
39
52
|
}>>;
|
|
40
53
|
export declare function createProcessFence(runner?: CommandRunner, options?: {
|
|
41
54
|
platform?: string;
|
|
55
|
+
selfPid?: number;
|
|
42
56
|
}): ProcessFence;
|
|
43
57
|
export declare function assertHostsStopped(fence: ProcessFence, env?: SetupEnvironment): Promise<void>;
|
|
@@ -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) {
|
|
@@ -131,6 +143,7 @@ export class ProcessFenceViolationError extends Error {
|
|
|
131
143
|
/** List processes before filtering hosts; Windows PID 0 is a valid idle-process row. */
|
|
132
144
|
export async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
|
|
133
145
|
const windows = (options.platform ?? process.platform) === 'win32';
|
|
146
|
+
const selfPid = options.selfPid ?? process.pid;
|
|
134
147
|
let inspection = {
|
|
135
148
|
step: windows ? 'tasklist' : 'ps',
|
|
136
149
|
exitCode: null,
|
|
@@ -168,6 +181,45 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
|
|
|
168
181
|
}
|
|
169
182
|
};
|
|
170
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
|
+
}
|
|
171
223
|
const result = await inspect(windows ? 'tasklist' : 'ps', windows ? 'tasklist.exe' : 'ps', windows ? ['/fo', 'csv', '/nh'] : ['-eo', 'pid,command']);
|
|
172
224
|
if (result.exitCode !== 0)
|
|
173
225
|
throw new ProcessInspectionError(inspection);
|
|
@@ -202,7 +254,7 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
|
|
|
202
254
|
if (!processes.length)
|
|
203
255
|
throw new ProcessInspectionError(inspection);
|
|
204
256
|
// tasklist identifies native hosts, but npm Pi/OpenCode scripts appear as Node or Bun.
|
|
205
|
-
const runtimes = processes.filter((entry) => entry.pid !==
|
|
257
|
+
const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
|
|
206
258
|
if (windows && runtimes.length && options.inspectRuntimes !== false) {
|
|
207
259
|
const details = await inspect('CIM', 'powershell.exe', [
|
|
208
260
|
'-NoProfile',
|
|
@@ -241,10 +293,15 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
|
|
|
241
293
|
}
|
|
242
294
|
}
|
|
243
295
|
export function createProcessFence(runner = defaultCommandRunner, options = {}) {
|
|
244
|
-
const
|
|
296
|
+
const selfPid = options.selfPid ?? process.pid;
|
|
297
|
+
const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
|
|
245
298
|
return {
|
|
246
299
|
async listRunningHosts(env) {
|
|
247
|
-
return (await listSetupProcesses(runner, {
|
|
300
|
+
return (await listSetupProcesses(runner, {
|
|
301
|
+
...options,
|
|
302
|
+
env,
|
|
303
|
+
hostImagesOnly: true,
|
|
304
|
+
})).filter(isHost);
|
|
248
305
|
},
|
|
249
306
|
async previewRunningHosts(env) {
|
|
250
307
|
const processes = await listSetupProcesses(runner, {
|
|
@@ -256,7 +313,7 @@ export function createProcessFence(runner = defaultCommandRunner, options = {})
|
|
|
256
313
|
return {
|
|
257
314
|
hosts: processes.filter(isHost),
|
|
258
315
|
uncheckedRuntimes: windows
|
|
259
|
-
? processes.filter((entry) => entry.pid !==
|
|
316
|
+
? processes.filter((entry) => entry.pid !== selfPid &&
|
|
260
317
|
/^(?:node|bun)\.exe$/i.test(entry.command)).length
|
|
261
318
|
: 0,
|
|
262
319
|
};
|
package/dist/setup/types.d.ts
CHANGED
|
@@ -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.
|
|
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": {
|