@cortexkit/common-auth 0.26.0 → 0.27.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.
@@ -10,6 +10,7 @@ import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, Pro
10
10
  import { selectSetupHosts } from './prompts.js';
11
11
  import { planOpenCodeRegistration, registerOpenCode, registerPi, } from './register.js';
12
12
  export const AMBIGUOUS_OPENCODE_MESSAGE = 'Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.';
13
+ const UNAVAILABLE_HOST_MESSAGE = 'Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.';
13
14
  function flags(argv) {
14
15
  const result = {
15
16
  yes: false,
@@ -17,6 +18,8 @@ function flags(argv) {
17
18
  claustrum: false,
18
19
  noClaustrum: false,
19
20
  login: false,
21
+ enrollOnly: false,
22
+ hosts: [],
20
23
  opencode: undefined,
21
24
  };
22
25
  for (const arg of argv) {
@@ -30,6 +33,14 @@ function flags(argv) {
30
33
  result.noClaustrum = true;
31
34
  else if (arg === '--login')
32
35
  result.login = true;
36
+ else if (arg === '--enroll-only')
37
+ result.enrollOnly = true;
38
+ else if (arg.startsWith('--host=')) {
39
+ const host = arg.slice('--host='.length);
40
+ if (host !== 'opencode' && host !== 'pi')
41
+ throw new Error(UNAVAILABLE_HOST_MESSAGE);
42
+ result.hosts.push(host);
43
+ }
33
44
  else if (/^--opencode=(1|2|both)$/.test(arg))
34
45
  result.opencode = arg.slice('--opencode='.length);
35
46
  else
@@ -39,6 +50,10 @@ function flags(argv) {
39
50
  throw new Error('--claustrum and --no-claustrum cannot be used together.');
40
51
  if (result.login && result.claustrum)
41
52
  throw new Error('--login and --claustrum cannot be used together.');
53
+ if (result.enrollOnly && result.login)
54
+ throw new Error('--enroll-only and --login cannot be used together.');
55
+ if (result.enrollOnly && result.noClaustrum)
56
+ throw new Error('--enroll-only and --no-claustrum cannot be used together.');
42
57
  return result;
43
58
  }
44
59
  function validatePlugin(plugin) {
@@ -96,14 +111,18 @@ export async function runSetup(plugin, argv = [], io = {}) {
96
111
  if (piWithoutCli)
97
112
  printLine(terminal, 'Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.');
98
113
  const found = ['opencode', 'pi'].filter((host) => detection[host].installed && !(host === 'pi' && piWithoutCli));
114
+ if (options.hosts.some((host) => !found.includes(host)))
115
+ throw new Error(UNAVAILABLE_HOST_MESSAGE);
99
116
  // A dry run changes nothing, so without a terminal it plans the --yes path
100
117
  // instead of refusing; scripts and CI can preview setup with --dry-run alone.
101
118
  const assumeYes = options.yes || (options.dryRun && !isInteractive(terminal));
102
119
  if (!assumeYes && !isInteractive(terminal))
103
120
  throw new Error('Setup requires a TTY or --yes.');
104
- const hosts = assumeYes
105
- ? found
106
- : ((await selectSetupHosts(terminal, found)) ?? []);
121
+ const hosts = options.hosts.length
122
+ ? found.filter((host) => options.hosts.includes(host))
123
+ : assumeYes
124
+ ? found
125
+ : ((await selectSetupHosts(terminal, found)) ?? []);
107
126
  let generation = options.opencode ??
108
127
  (detection.opencode.generation === 'ambiguous'
109
128
  ? '1'
@@ -160,9 +179,10 @@ export async function runSetup(plugin, argv = [], io = {}) {
160
179
  }
161
180
  else
162
181
  await stopped();
163
- if (options.claustrum && !detection.claustrum.available)
164
- throw new Error('Claustrum is not available. Start ck or use --no-claustrum for local sign-in.');
165
- let useVault = Boolean(options.claustrum);
182
+ if ((options.claustrum || options.enrollOnly) &&
183
+ !detection.claustrum.available)
184
+ throw new Error('Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.');
185
+ let useVault = options.claustrum || options.enrollOnly;
166
186
  if (!useVault &&
167
187
  !options.login &&
168
188
  !options.noClaustrum &&
@@ -182,10 +202,20 @@ export async function runSetup(plugin, argv = [], io = {}) {
182
202
  useVault = choice === true;
183
203
  }
184
204
  const mode = useVault ? 'claustrum' : 'local';
185
- // Validate every config before login or enrollment can change credential state.
186
- const writes = hosts.includes('opencode')
205
+ // Validate configs before changing credentials; enrollment-only needs no registration plan.
206
+ const writes = !options.enrollOnly && hosts.includes('opencode')
187
207
  ? planOpenCodeRegistration(plugin, generation, io)
188
208
  : [];
209
+ for (const write of writes) {
210
+ for (const entry of write.existingLocalEntries ?? [])
211
+ printLine(terminal, `OpenCode: already registered from ${entry} in ${write.path}.`);
212
+ const entries = [
213
+ ...(write.existingLocalEntries ?? []),
214
+ ...(write.existingNpmEntries ?? []),
215
+ ];
216
+ if (entries.length > 1)
217
+ printLine(terminal, `Warning: ${plugin.displayName} may load twice in ${write.path}: ${entries.join(', ')}. Entries were left unchanged.`);
218
+ }
189
219
  if (options.dryRun) {
190
220
  printLine(terminal, 'Dry run: no registrations, enrollment, sign-in or migration will be performed.');
191
221
  for (const host of hosts) {
@@ -197,15 +227,16 @@ export async function runSetup(plugin, argv = [], io = {}) {
197
227
  }
198
228
  else
199
229
  printLine(terminal, `Would sign in locally for ${host}.`);
200
- if (plugin.beforeRegister)
230
+ if (!options.enrollOnly && plugin.beforeRegister)
201
231
  printLine(terminal, `Would run beforeRegister(${host}, ${mode}).`);
202
232
  }
203
233
  for (const write of writes)
204
234
  printLine(terminal, `${write.changed ? 'Would write' : 'Unchanged'} ${write.path}:\n${write.content}`);
205
- if (hosts.includes('pi'))
235
+ if (!options.enrollOnly && hosts.includes('pi'))
206
236
  printLine(terminal, `Would run ${detection.pi.executable} install npm:${plugin.packages.pi}@${plugin.version}`);
207
- for (const host of hosts)
208
- printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
237
+ if (!options.enrollOnly)
238
+ for (const host of hosts)
239
+ printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
209
240
  }
210
241
  else {
211
242
  const context = {
@@ -237,6 +268,8 @@ export async function runSetup(plugin, argv = [], io = {}) {
237
268
  else
238
269
  await plugin.signInLocal(host, context);
239
270
  await stopped();
271
+ if (options.enrollOnly)
272
+ continue;
240
273
  await plugin.beforeRegister?.(host, mode, context);
241
274
  await stopped();
242
275
  if (host === 'opencode')
@@ -265,7 +298,12 @@ export async function runSetup(plugin, argv = [], io = {}) {
265
298
  throw error;
266
299
  }
267
300
  }
268
- printLine(terminal, `${options.dryRun ? 'Planned' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
269
- printLine(terminal, `Next: ${hosts.includes('opencode') ? 'start OpenCode' : 'start Pi'} and run ${plugin.slashCommand}.`);
301
+ printLine(terminal, `${options.dryRun ? 'Planned' : options.enrollOnly ? 'Enrolled' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
302
+ if (options.enrollOnly) {
303
+ printLine(terminal, `Enroll-only: no host config or plugin registration ${options.dryRun ? 'will be' : 'was'} written.`);
304
+ printLine(terminal, 'Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.');
305
+ }
306
+ else
307
+ printLine(terminal, `Next: ${hosts.includes('opencode') ? 'start OpenCode' : 'start Pi'} and run ${plugin.slashCommand}.`);
270
308
  return { hosts, dryRun: options.dryRun, mode, detection };
271
309
  }
@@ -3,6 +3,8 @@ export interface PlannedWrite {
3
3
  path: string;
4
4
  content: string;
5
5
  changed: boolean;
6
+ existingLocalEntries?: string[];
7
+ existingNpmEntries?: string[];
6
8
  }
7
9
  /** Edit only array entries so unrelated JSONC text, including comments, survives. */
8
10
  export declare function updatePluginConfig(text: string, key: 'plugin' | 'plugins', pkg: string, version: string): string;
@@ -1,10 +1,11 @@
1
+ import { domainToUnicode } from 'node:url';
1
2
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, } from 'jsonc-parser';
2
3
  import { SetupCommandError } from './command-error.js';
3
4
  import { defaultCommandRunner, runResolvedCommand } from './command-runner.js';
4
5
  import { writeHostConfigAtomic } from './config-write.js';
5
6
  import { defaultSetupFileSystem } from './detect.js';
6
7
  import { setupPaths } from './paths.js';
7
- function packageOf(value) {
8
+ function specifierOf(value) {
8
9
  const entry = typeof value === 'string'
9
10
  ? value
10
11
  : Array.isArray(value)
@@ -12,11 +13,72 @@ function packageOf(value) {
12
13
  : value && typeof value === 'object' && 'package' in value
13
14
  ? value.package
14
15
  : null;
15
- if (typeof entry !== 'string')
16
+ return typeof entry === 'string' ? entry : null;
17
+ }
18
+ function packageOf(value) {
19
+ const entry = specifierOf(value);
20
+ if (entry === null)
16
21
  return null;
17
22
  const at = entry.indexOf('@', entry.startsWith('@') ? 1 : 0);
18
23
  return at < 0 ? entry : entry.slice(0, at);
19
24
  }
25
+ function localFileURL(entry, windows) {
26
+ const url = new URL(entry);
27
+ if (/%2f/i.test(url.pathname) || (windows && /%5c/i.test(url.pathname)))
28
+ throw new Error('Encoded path separators are not valid in a file URL.');
29
+ const decoded = decodeURIComponent(url.pathname);
30
+ if (!windows) {
31
+ if (url.hostname)
32
+ throw new Error('A POSIX file URL must be local.');
33
+ return decoded;
34
+ }
35
+ const pathname = decoded.replaceAll('/', '\\');
36
+ if (url.hostname)
37
+ return `\\\\${domainToUnicode(url.hostname)}${pathname}`;
38
+ if (!/^\\[a-z]:/i.test(pathname))
39
+ throw new Error('A Windows file URL must have an absolute drive path.');
40
+ return pathname.slice(1);
41
+ }
42
+ function localPackageOf(entry, configFile, io) {
43
+ const { path, platform } = setupPaths(io);
44
+ try {
45
+ // Relative paths use the declaring config's directory, not setup's working directory:
46
+ // https://github.com/anomalyco/opencode/blob/b6478dce/packages/opencode/src/config/plugin.ts#L40-L60
47
+ // https://github.com/anomalyco/opencode/blob/v2.0.22/packages/core/src/config/plugin/source.ts#L139-L145
48
+ // Decode file URLs explicitly: Bun 1.3 ignores fileURLToPath's Windows override.
49
+ // The requested platform, not the OS running setup's tests, determines path rules.
50
+ const directory = /^file:\/\//i.test(entry)
51
+ ? localFileURL(entry, platform === 'win32')
52
+ : path.isAbsolute(entry) || entry.startsWith('.')
53
+ ? path.resolve(path.dirname(configFile), entry)
54
+ : null;
55
+ if (directory === null)
56
+ return null;
57
+ const manifest = JSON.parse((io.fs ?? defaultSetupFileSystem).readText(path.join(directory, 'package.json')));
58
+ return manifest &&
59
+ typeof manifest === 'object' &&
60
+ 'name' in manifest &&
61
+ typeof manifest.name === 'string'
62
+ ? manifest.name
63
+ : null;
64
+ }
65
+ catch {
66
+ // A missing, unreadable or invalid local package is not a registration of this plugin.
67
+ return null;
68
+ }
69
+ }
70
+ function pluginConfig(text, key) {
71
+ const errors = [];
72
+ const value = parse(text, errors, { allowTrailingComma: true });
73
+ if (errors.length ||
74
+ !value ||
75
+ typeof value !== 'object' ||
76
+ Array.isArray(value))
77
+ throw new Error('Invalid OpenCode config; refusing to overwrite it.');
78
+ if (value[key] !== undefined && !Array.isArray(value[key]))
79
+ throw new Error(`OpenCode ${key} must be an array.`);
80
+ return value;
81
+ }
20
82
  function removeArrayEntry(text, key, index) {
21
83
  const tree = parseTree(text);
22
84
  const array = tree && findNodeAtLocation(tree, [key]);
@@ -48,13 +110,7 @@ function removeArrayEntry(text, key, index) {
48
110
  }
49
111
  /** Edit only array entries so unrelated JSONC text, including comments, survives. */
50
112
  export function updatePluginConfig(text, key, pkg, version) {
51
- const errors = [];
52
- const value = parse(text, errors, { allowTrailingComma: true });
53
- if (errors.length ||
54
- !value ||
55
- typeof value !== 'object' ||
56
- Array.isArray(value))
57
- throw new Error('Invalid OpenCode config; refusing to overwrite it.');
113
+ const value = pluginConfig(text, key);
58
114
  const options = {
59
115
  formattingOptions: {
60
116
  insertSpaces: !/^\t+/m.test(text),
@@ -64,8 +120,6 @@ export function updatePluginConfig(text, key, pkg, version) {
64
120
  };
65
121
  let output = text;
66
122
  const array = value[key];
67
- if (array !== undefined && !Array.isArray(array))
68
- throw new Error(`OpenCode ${key} must be an array.`);
69
123
  const entries = Array.isArray(array) ? [...array] : [];
70
124
  const matches = entries.flatMap((entry, index) => packageOf(entry) === pkg ? [index] : []);
71
125
  const entry = `${pkg}@${version}`;
@@ -109,6 +163,31 @@ export function planOpenCodeRegistration(plugin, generation, io = {}) {
109
163
  const before = exists
110
164
  ? fs.readText(file)
111
165
  : `${JSON.stringify({ $schema: `https://opencode.ai/${name === 'tui' ? 'tui' : 'config'}.json` }, null, 2)}\n`;
166
+ const config = pluginConfig(before, key);
167
+ const existingLocalEntries = [];
168
+ const existingNpmEntries = [];
169
+ for (const field of ['plugin', 'plugins']) {
170
+ if (!Array.isArray(config[field]))
171
+ continue;
172
+ for (const entry of config[field]) {
173
+ const spec = specifierOf(entry);
174
+ if (spec === null)
175
+ continue;
176
+ if (localPackageOf(spec, file, io) === plugin.packages.opencode)
177
+ existingLocalEntries.push(JSON.stringify(entry));
178
+ else if (packageOf(entry) === plugin.packages.opencode)
179
+ existingNpmEntries.push(JSON.stringify(entry));
180
+ }
181
+ }
182
+ // A local build is deliberate: do not replace it, deduplicate it or migrate its key.
183
+ if (existingLocalEntries.length > 0)
184
+ return {
185
+ path: file,
186
+ content: before,
187
+ changed: false,
188
+ existingLocalEntries,
189
+ existingNpmEntries,
190
+ };
112
191
  const content = updatePluginConfig(before, key, plugin.packages.opencode, plugin.version);
113
192
  return { path: file, content, changed: !exists || content !== before };
114
193
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.26.0",
3
+ "version": "0.27.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": {
@@ -36,6 +36,10 @@
36
36
  "types": "./dist/logger/index.d.ts",
37
37
  "import": "./dist/logger/index.js"
38
38
  },
39
+ "./redaction": {
40
+ "types": "./dist/redaction/index.d.ts",
41
+ "import": "./dist/redaction/index.js"
42
+ },
39
43
  "./sidebar-file": {
40
44
  "types": "./dist/sidebar-file/index.d.ts",
41
45
  "import": "./dist/sidebar-file/index.js"
@@ -95,7 +99,7 @@
95
99
  "scripts": {
96
100
  "build": "bun scripts/check-local-deps.mjs && bun scripts/check-installed-ranges.mjs && tsc -p tsconfig.build.json && bun scripts/check-private-files-external.ts",
97
101
  "test": "bun test",
98
- "typecheck": "tsc --noEmit",
102
+ "typecheck": "tsc --noEmit && tsc -p test/redaction/tsconfig.json --noEmit",
99
103
  "types": "bun run typecheck",
100
104
  "format": "biome check --write --unsafe .",
101
105
  "format:check": "biome format .",