@cortexkit/common-auth 0.27.0 → 0.28.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.
@@ -0,0 +1,50 @@
1
+ import type { OpenCodeGeneration, SetupHost } from './types.js';
2
+ export declare const UNAVAILABLE_HOST_MESSAGE = "Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.";
3
+ type SwitchKey = 'yes' | 'dryRun' | 'claustrum' | 'noClaustrum' | 'login' | 'enrollOnly';
4
+ /**
5
+ * One flag the shared setup parser accepts. A switch sets `key` to true; a
6
+ * value flag takes one of `values` as `--name=value`, and also as the next
7
+ * argument (`--name value`) when `spaceForm` is set. `invalid` replaces the
8
+ * unknown-argument refusal when a value flag gets a value it does not accept.
9
+ */
10
+ export type SetupFlag = {
11
+ name: string;
12
+ key: SwitchKey;
13
+ description: string;
14
+ } | {
15
+ name: string;
16
+ key: 'hosts' | 'opencode';
17
+ values: readonly string[];
18
+ spaceForm?: boolean;
19
+ invalid?: string;
20
+ description: string;
21
+ };
22
+ /**
23
+ * Every flag `runSetup` accepts. The parser and `setupUsage` both read this
24
+ * table, so the help a plugin prints cannot list a flag the parser refuses or
25
+ * leave out one it accepts.
26
+ */
27
+ export declare const SETUP_FLAGS: readonly SetupFlag[];
28
+ export interface SetupFlags {
29
+ yes: boolean;
30
+ dryRun: boolean;
31
+ claustrum: boolean;
32
+ noClaustrum: boolean;
33
+ login: boolean;
34
+ enrollOnly: boolean;
35
+ hosts: SetupHost[];
36
+ opencode: OpenCodeGeneration | undefined;
37
+ }
38
+ /** Parse setup's arguments against `SETUP_FLAGS`, refusing anything else. */
39
+ export declare function parseSetupFlags(argv: readonly string[]): SetupFlags;
40
+ /**
41
+ * The flags `runSetup` accepts, one per line, for a plugin's `setup --help`.
42
+ * The shared parser has no `--help` of its own: the plugin's bin checks for
43
+ * `--help` or `-h` before calling `runSetup`, prints this text and any lines of
44
+ * its own, and exits 0. With `command` the text starts with a usage line, such
45
+ * as `Usage: example-auth setup [flags]`.
46
+ */
47
+ export declare function setupUsage(options?: {
48
+ command?: string;
49
+ }): string;
50
+ export {};
@@ -0,0 +1,123 @@
1
+ export const UNAVAILABLE_HOST_MESSAGE = 'Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.';
2
+ /**
3
+ * Every flag `runSetup` accepts. The parser and `setupUsage` both read this
4
+ * table, so the help a plugin prints cannot list a flag the parser refuses or
5
+ * leave out one it accepts.
6
+ */
7
+ export const SETUP_FLAGS = [
8
+ {
9
+ name: '--yes',
10
+ key: 'yes',
11
+ description: 'Run without questions and set up every found host. Does not choose the vault.',
12
+ },
13
+ {
14
+ name: '--dry-run',
15
+ key: 'dryRun',
16
+ description: 'Print what setup would do without changing anything.',
17
+ },
18
+ {
19
+ name: '--host',
20
+ key: 'hosts',
21
+ values: ['opencode', 'pi'],
22
+ spaceForm: true,
23
+ invalid: UNAVAILABLE_HOST_MESSAGE,
24
+ description: 'Set up only this host; repeat the flag for both. Also written --host=<host>.',
25
+ },
26
+ {
27
+ name: '--opencode',
28
+ key: 'opencode',
29
+ values: ['1', '2', 'both'],
30
+ description: 'Register for this OpenCode generation.',
31
+ },
32
+ {
33
+ name: '--claustrum',
34
+ key: 'claustrum',
35
+ description: 'Connect the hosts to the Claustrum vault.',
36
+ },
37
+ {
38
+ name: '--no-claustrum',
39
+ key: 'noClaustrum',
40
+ description: 'Do not offer the Claustrum vault; sign in locally.',
41
+ },
42
+ {
43
+ name: '--login',
44
+ key: 'login',
45
+ description: 'Sign in locally instead of using the Claustrum vault.',
46
+ },
47
+ {
48
+ name: '--enroll-only',
49
+ key: 'enrollOnly',
50
+ description: 'Only connect the hosts to the Claustrum vault; register nothing and migrate nothing.',
51
+ },
52
+ ];
53
+ function unknownArgument(arg) {
54
+ return new Error(`Unknown setup argument: ${arg}. Run the plugin's own setup --help to list the flags setup accepts.`);
55
+ }
56
+ /** Parse setup's arguments against `SETUP_FLAGS`, refusing anything else. */
57
+ export function parseSetupFlags(argv) {
58
+ const result = {
59
+ yes: false,
60
+ dryRun: false,
61
+ claustrum: false,
62
+ noClaustrum: false,
63
+ login: false,
64
+ enrollOnly: false,
65
+ hosts: [],
66
+ opencode: undefined,
67
+ };
68
+ for (let index = 0; index < argv.length; index++) {
69
+ const arg = argv[index];
70
+ const equals = arg.indexOf('=');
71
+ const name = equals === -1 ? arg : arg.slice(0, equals);
72
+ const flag = SETUP_FLAGS.find((entry) => entry.name === name);
73
+ if (!flag)
74
+ throw unknownArgument(arg);
75
+ if (!('values' in flag)) {
76
+ if (equals !== -1)
77
+ throw unknownArgument(arg);
78
+ result[flag.key] = true;
79
+ continue;
80
+ }
81
+ let value;
82
+ if (equals !== -1)
83
+ value = arg.slice(equals + 1);
84
+ else if (flag.spaceForm)
85
+ value = argv[++index];
86
+ else
87
+ throw unknownArgument(arg);
88
+ if (value === undefined || !flag.values.includes(value))
89
+ throw flag.invalid ? new Error(flag.invalid) : unknownArgument(arg);
90
+ if (flag.key === 'hosts')
91
+ result.hosts.push(value);
92
+ else
93
+ result.opencode = value;
94
+ }
95
+ if (result.claustrum && result.noClaustrum)
96
+ throw new Error('--claustrum and --no-claustrum cannot be used together.');
97
+ if (result.login && result.claustrum)
98
+ throw new Error('--login and --claustrum cannot be used together.');
99
+ if (result.enrollOnly && result.login)
100
+ throw new Error('--enroll-only and --login cannot be used together.');
101
+ if (result.enrollOnly && result.noClaustrum)
102
+ throw new Error('--enroll-only and --no-claustrum cannot be used together.');
103
+ return result;
104
+ }
105
+ /**
106
+ * The flags `runSetup` accepts, one per line, for a plugin's `setup --help`.
107
+ * The shared parser has no `--help` of its own: the plugin's bin checks for
108
+ * `--help` or `-h` before calling `runSetup`, prints this text and any lines of
109
+ * its own, and exits 0. With `command` the text starts with a usage line, such
110
+ * as `Usage: example-auth setup [flags]`.
111
+ */
112
+ export function setupUsage(options = {}) {
113
+ const labels = SETUP_FLAGS.map((flag) => 'values' in flag
114
+ ? `${flag.name}${flag.spaceForm ? ' ' : '='}${flag.values.join('|')}`
115
+ : flag.name);
116
+ const width = Math.max(...labels.map((label) => label.length));
117
+ const lines = SETUP_FLAGS.map((flag, index) => ` ${labels[index].padEnd(width)} ${flag.description}`);
118
+ return [
119
+ ...(options.command ? [`Usage: ${options.command} [flags]`, ''] : []),
120
+ 'Flags:',
121
+ ...lines,
122
+ ].join('\n');
123
+ }
@@ -2,6 +2,7 @@ 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
4
  export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, type HostNotEnrolledReason, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
5
+ export { setupUsage } from './flags.js';
5
6
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
6
7
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
7
8
  export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -2,5 +2,6 @@ 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
4
  export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
5
+ export { setupUsage } from './flags.js';
5
6
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
7
  export { planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
@@ -61,7 +61,13 @@ export interface SetupPlugin {
61
61
  */
62
62
  beforeSignIn?(host: SetupHost, context: SetupCallbackContext): Promise<void>;
63
63
  signInLocal(host: SetupHost, context: SetupCallbackContext): Promise<void>;
64
- migrate(host: SetupHost, context: SetupCallbackContext): Promise<void>;
64
+ /**
65
+ * Moves the host's existing provider credentials into place after the host
66
+ * is registered. Optional: a plugin with nothing to migrate (one that only
67
+ * reads credentials from the vault) leaves it out, and setup then neither
68
+ * calls it nor mentions migration in its dry-run plan.
69
+ */
70
+ migrate?(host: SetupHost, context: SetupCallbackContext): Promise<void>;
65
71
  /** Reject mixed local/vault credentials and activate provider-specific vault access before registration. */
66
72
  beforeRegister?(host: SetupHost, mode: 'local' | 'claustrum', context: SetupCallbackContext): Promise<void>;
67
73
  }
@@ -52,6 +52,8 @@ export type ReadResult = ({
52
52
  kind?: 'snapshot-contended';
53
53
  retryable?: true;
54
54
  };
55
+ /** Settings need only the config classification, not a joined roster snapshot. */
56
+ export declare function readPoolConfig(path: string): Promise<import("./schema.js").ConfigClassification>;
55
57
  /**
56
58
  * Validate config/state/config bytes without locks. Roster replacement writes
57
59
  * config before deleting old state credentials. Re-read a changed config so an
@@ -28,6 +28,10 @@ function parseFile(text) {
28
28
  return { exists: true, parseError };
29
29
  }
30
30
  }
31
+ /** Settings need only the config classification, not a joined roster snapshot. */
32
+ export async function readPoolConfig(path) {
33
+ return classifyConfig(parseFile(await readText(path)));
34
+ }
31
35
  /**
32
36
  * Validate config/state/config bytes without locks. Roster replacement writes
33
37
  * config before deleting old state credentials. Re-read a changed config so an
@@ -1,3 +1,4 @@
1
+ import type { QuotaCommitTimer } from '../quota/commit-interval.js';
1
2
  import { type Attribution } from './attribution.js';
2
3
  import type { PoolOperationError } from './errors.js';
3
4
  import type { PoolLogger } from './hooks.js';
@@ -24,11 +25,15 @@ export interface OpenPoolStoreOptions {
24
25
  * older reading replaces. Accepted readings appear in read/load
25
26
  * immediately, merged the same way; the returned promise still rejects
26
27
  * current-row refusals before queueing. Await dispose or close at shutdown
27
- * to drain.
28
+ * to attempt a bounded drain; readings still pending at its timeout are
29
+ * discarded. Normal quota commits are at least 30 seconds apart; a full
30
+ * queue commits early so response handling never waits for that interval.
28
31
  */
29
32
  coalesceQuota?: boolean;
30
33
  /** Bounded quota drain on close/dispose, in milliseconds; defaults to 1,000. */
31
34
  quotaDrainTimeoutMs?: number;
35
+ /** Monotonic clock and scheduling seam for detached quota commits. */
36
+ quotaCommitTimer?: QuotaCommitTimer;
32
37
  /**
33
38
  * The codec of the provider state kept beside each row's credential (see
34
39
  * `ProviderStateCodec`). Without it no row shows a provider state, and
@@ -82,7 +82,7 @@ export function openPoolStore(options) {
82
82
  firePull: (id, reason) => pulls.fire(id, reason),
83
83
  };
84
84
  const quotaWriter = options.coalesceQuota
85
- ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs)
85
+ ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs, options.quotaCommitTimer)
86
86
  : undefined;
87
87
  const record = (id, attribution, observation) => quotaWriter
88
88
  ? quotaWriter.record(id, attribution, observation)
@@ -1,3 +1,4 @@
1
+ import { type QuotaCommitTimer } from '../quota/commit-interval.js';
1
2
  import { type Attribution } from './attribution.js';
2
3
  import { type StoreRuntime } from './runtime.js';
3
4
  import { type PoolRow } from './schema.js';
@@ -14,17 +15,19 @@ export declare const POOL_QUOTA_QUEUE_LIMIT = 128;
14
15
  export declare class PoolQuotaWriter {
15
16
  private readonly rt;
16
17
  private readonly timeoutMs;
18
+ private readonly clock;
17
19
  private readonly pending;
18
20
  private readonly warned;
19
21
  private readonly wake;
20
22
  private readonly logger;
21
23
  private timer?;
24
+ private committedAt?;
22
25
  private running?;
23
26
  private closing?;
24
27
  private closed;
25
28
  private stopped;
26
29
  private failures;
27
- constructor(rt: StoreRuntime, timeoutMs?: number);
30
+ constructor(rt: StoreRuntime, timeoutMs?: number, clock?: QuotaCommitTimer);
28
31
  record(id: string, attribution: Attribution, observation: unknown): Promise<void>;
29
32
  private queued;
30
33
  private room;
@@ -32,6 +35,7 @@ export declare class PoolQuotaWriter {
32
35
  private overlayRow;
33
36
  overlay(rows: PoolRow[]): PoolRow[];
34
37
  private schedule;
38
+ private cancelTimer;
35
39
  private flushNow;
36
40
  private flush;
37
41
  private warn;
@@ -1,4 +1,5 @@
1
1
  import { createLogger } from '../logger/index.js';
2
+ import { QUOTA_COMMIT_INTERVAL_MS, quotaCommitTimer, } from '../quota/commit-interval.js';
2
3
  import { assertQuotaEpoch, assertQuotaRow, mergedQuota, } from './attribution.js';
3
4
  import { PoolOperationError } from './errors.js';
4
5
  import { toFailure, withTransaction } from './mutate.js';
@@ -24,19 +25,22 @@ export const POOL_QUOTA_QUEUE_LIMIT = 128;
24
25
  export class PoolQuotaWriter {
25
26
  rt;
26
27
  timeoutMs;
28
+ clock;
27
29
  pending = new Map();
28
30
  warned = new Set();
29
31
  wake = new Set();
30
32
  logger;
31
33
  timer;
34
+ committedAt;
32
35
  running;
33
36
  closing;
34
37
  closed = false;
35
38
  stopped = false;
36
39
  failures = 0;
37
- constructor(rt, timeoutMs = 1_000) {
40
+ constructor(rt, timeoutMs = 1_000, clock = quotaCommitTimer) {
38
41
  this.rt = rt;
39
42
  this.timeoutMs = timeoutMs;
43
+ this.clock = clock;
40
44
  this.logger = rt.ctx.logger ?? createLogger('store');
41
45
  }
42
46
  async record(id, attribution, observation) {
@@ -126,25 +130,33 @@ export class PoolQuotaWriter {
126
130
  schedule(delay) {
127
131
  if (this.running || this.timer || !this.pending.size || this.stopped)
128
132
  return;
129
- this.timer = setTimeout(() => {
133
+ const remaining = this.closed
134
+ ? 0
135
+ : (this.committedAt ?? -Infinity) +
136
+ QUOTA_COMMIT_INTERVAL_MS -
137
+ this.clock.now();
138
+ this.timer = this.clock.schedule(Math.max(delay, remaining), () => {
130
139
  this.timer = undefined;
131
- this.flush();
132
- }, delay);
140
+ return this.flush();
141
+ });
133
142
  if (!this.closed)
134
143
  this.timer.unref?.();
135
144
  }
136
- // Starts a flush now rather than at the coalescing timer or retry backoff;
137
- // a flush already running is left to finish.
145
+ cancelTimer() {
146
+ this.timer?.cancel();
147
+ this.timer = undefined;
148
+ }
149
+ // A full queue overrides the interval: response handling must not wait for
150
+ // a quota commit slot. A flush already running is left to finish.
138
151
  flushNow() {
139
152
  if (this.running)
140
153
  return;
141
- clearTimeout(this.timer);
142
- this.timer = undefined;
154
+ this.cancelTimer();
143
155
  this.flush();
144
156
  }
145
157
  flush() {
146
158
  if (this.running || this.stopped || !this.pending.size)
147
- return;
159
+ return this.running ?? Promise.resolve();
148
160
  // Every queued reading, each row's in arrival order.
149
161
  const batch = [...this.pending.values()].flat();
150
162
  // Short lock attempts allow retries to pick up freshly queued readings and
@@ -208,8 +220,10 @@ export class PoolQuotaWriter {
208
220
  tx.setEntry(id, { ...entry, quota, needsFirstReading: false });
209
221
  changed = true;
210
222
  }
211
- if (changed && !this.stopped)
223
+ if (changed && !this.stopped) {
212
224
  await tx.commitConfig();
225
+ this.committedAt = this.clock.now();
226
+ }
213
227
  }, { completeTorn: false });
214
228
  const flushed = new Set(batch);
215
229
  for (const [id, queue] of this.pending) {
@@ -240,6 +254,7 @@ export class PoolQuotaWriter {
240
254
  this.schedule(delay);
241
255
  }
242
256
  })();
257
+ return this.running;
243
258
  }
244
259
  warn(message, data) {
245
260
  try {
@@ -257,8 +272,7 @@ export class PoolQuotaWriter {
257
272
  return this.closing;
258
273
  }
259
274
  async drain() {
260
- clearTimeout(this.timer);
261
- this.timer = undefined;
275
+ this.cancelTimer();
262
276
  let deadline;
263
277
  let wake;
264
278
  const drained = new Promise((done) => {
@@ -281,7 +295,7 @@ export class PoolQuotaWriter {
281
295
  finally {
282
296
  this.stopped = true;
283
297
  clearTimeout(deadline);
284
- clearTimeout(this.timer);
298
+ this.cancelTimer();
285
299
  this.wake.delete(wake);
286
300
  if (this.pending.size)
287
301
  this.warn('pool quota drain timed out; pending readings left', {
@@ -50,7 +50,7 @@ export type UpdateSettingsResult = {
50
50
  /** `unchanged` when the mutator left the settings as they were; nothing was written. */
51
51
  outcome: 'updated' | 'unchanged';
52
52
  };
53
- /** Reads the settings without taking a lock or writing anything. */
53
+ /** Reads only the config's settings, without taking a lock or writing anything. */
54
54
  export declare function readPoolSettings(rt: StoreRuntime): Promise<SettingsRead>;
55
55
  /**
56
56
  * One locked read-modify-write of the plugin's settings in the config file
@@ -1,8 +1,10 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
2
  import { writeJsonAtomic } from '../fs/atomic-write.js';
3
+ import { FileReadCache } from '../fs/file-read-cache.js';
4
+ import { windowsPrivateFiles } from '../fs/private-files.js';
3
5
  import { PoolOperationError } from './errors.js';
4
6
  import { assertNotInsideHook, runInsideHook } from './hooks.js';
5
- import { notReadyError, readPool, runOperation } from './mutate.js';
7
+ import { notReadyError, readPool, readPoolConfig, runOperation, } from './mutate.js';
6
8
  import { isRecord, POOL_KEY } from './schema.js';
7
9
  /**
8
10
  * Top-level config keys the pool owns: the legacy `version`, the legacy
@@ -58,12 +60,20 @@ function settingsRefusal(message) {
58
60
  message,
59
61
  });
60
62
  }
61
- /** Reads the settings without taking a lock or writing anything. */
63
+ const settingsCache = new FileReadCache();
64
+ /** Reads only the config's settings, without taking a lock or writing anything. */
62
65
  export async function readPoolSettings(rt) {
63
- const result = await readPool(rt.ctx);
64
- if (result.status === 'error')
65
- return result;
66
- return { status: result.status, settings: settingsOf(result.config) };
66
+ const read = async ([configPath = rt.ctx.configPath,] = []) => {
67
+ const result = await readPoolConfig(configPath);
68
+ if (result.status === 'error')
69
+ return { status: 'error', file: 'config', reason: result.reason };
70
+ return { status: result.status, settings: settingsOf(result.config) };
71
+ };
72
+ // Native Windows security checks cannot be replaced by a stat fingerprint.
73
+ const result = windowsPrivateFiles
74
+ ? await read()
75
+ : await settingsCache.read([rt.ctx.configPath], read);
76
+ return structuredClone(result);
67
77
  }
68
78
  /**
69
79
  * One locked read-modify-write of the plugin's settings in the config file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.27.0",
3
+ "version": "0.28.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": {