@h1r-ai/croche-cli 0.5.5 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +267 -148
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/dist/bin.js +29 -25
  4. package/dist/chunk-66EUX7EL.js +165 -0
  5. package/dist/chunk-DKT5HHSB.js +532 -0
  6. package/dist/chunk-K3UDT4EM.js +3110 -0
  7. package/dist/collector-credential.d.ts +9 -0
  8. package/dist/config-authoring.d.ts +19 -0
  9. package/dist/config-bases.d.ts +17 -0
  10. package/dist/config-push-base-35HX67AJ.js +2254 -0
  11. package/dist/config-push-base.d.ts +7 -0
  12. package/dist/control-address.d.ts +2 -0
  13. package/dist/control-server.d.ts +12 -15
  14. package/dist/control-server.js +9 -288
  15. package/dist/control-v2-auth.d.ts +24 -0
  16. package/dist/control-v2-capture.d.ts +34 -0
  17. package/dist/control-v2-json.d.ts +15 -0
  18. package/dist/control-v2-state.d.ts +90 -0
  19. package/dist/credentials.d.ts +2 -2
  20. package/dist/debugger/public/index.html +1 -0
  21. package/dist/debugger/public/stage-control.js +84 -0
  22. package/dist/debugger/public/stage-manifest.js +45 -0
  23. package/dist/debugger/public/stage-model.js +103 -0
  24. package/dist/debugger/public/stage-targets.js +18 -0
  25. package/dist/debugger/public/stage.css +459 -0
  26. package/dist/debugger/public/stage.html +17 -0
  27. package/dist/debugger/public/stage.js +113 -0
  28. package/dist/debugger/server/collector.js +42 -26
  29. package/dist/debugger/server/control-bridge.js +113 -0
  30. package/dist/debugger/server/server.js +10 -1
  31. package/dist/debugger/server/viewer-security.js +12 -0
  32. package/dist/debugger.d.ts +16 -6
  33. package/dist/index.d.ts +8 -1
  34. package/dist/index.js +17 -321
  35. package/dist/json-result.d.ts +2 -0
  36. package/package.json +2 -1
  37. package/dist/config.js +0 -100
  38. package/dist/control-client.js +0 -65
  39. package/dist/core-defaults.js +0 -2
  40. package/dist/credentials.js +0 -136
  41. package/dist/debug-keys.js +0 -141
  42. package/dist/debugger.js +0 -469
  43. package/dist/help.js +0 -158
  44. package/dist/text-file.js +0 -15
@@ -1,136 +0,0 @@
1
- import { homedir } from 'node:os';
2
- import path from 'node:path';
3
- import { mkdir, chmod, lstat, readFile, open, rename, unlink } from 'node:fs/promises';
4
- import { randomUUID } from 'node:crypto';
5
- import { CliError } from './index.js';
6
- export const validCredential = (key) => /^dk_[A-Za-z0-9_-]{32,256}$/.test(key) && !key.includes('\n');
7
- export function credentialPath(env, platform = process.platform, home = env.HOME ?? homedir()) {
8
- if (platform === 'win32') {
9
- const profile = env.USERPROFILE, appData = env.APPDATA;
10
- if (!profile || !appData || !path.win32.isAbsolute(profile) || !path.win32.isAbsolute(appData))
11
- throw new CliError('invalid_configuration', 'A user-profile application-data directory is required.');
12
- const relative = path.win32.relative(profile, appData);
13
- if (relative === '..' || relative.startsWith('..\\') || path.win32.isAbsolute(relative))
14
- throw new CliError('invalid_configuration', 'Credential storage must be inside the current user profile.');
15
- return path.win32.join(appData, 'croche', 'credentials.json');
16
- }
17
- const root = platform === 'darwin' ? path.join(home, 'Library', 'Application Support') : env.XDG_CONFIG_HOME ?? path.join(home, '.config');
18
- if (!path.isAbsolute(root))
19
- throw new CliError('invalid_configuration', 'The configuration directory must be absolute.');
20
- return path.join(root, 'croche', 'credentials.json');
21
- }
22
- /** The account key from CROCHE_ACCOUNT_KEY, or from its older name CROCHE_DEVELOPER_KEY. Both set to different values is refused. */
23
- export function environmentCredential(env) {
24
- const current = env.CROCHE_ACCOUNT_KEY, older = env.CROCHE_DEVELOPER_KEY;
25
- if (current !== undefined && older !== undefined && current !== older)
26
- throw new CliError('invalid_configuration', 'CROCHE_ACCOUNT_KEY and CROCHE_DEVELOPER_KEY are both set and differ; unset one.');
27
- return current ?? older;
28
- }
29
- /** The environment variables that currently hold an account key, newest name first. */
30
- export function environmentCredentialNames(env) {
31
- return ['CROCHE_ACCOUNT_KEY', 'CROCHE_DEVELOPER_KEY'].filter(name => env[name] !== undefined);
32
- }
33
- export async function resolveCredential(env) {
34
- // An explicit environment credential always takes precedence over disk.
35
- const fromEnv = environmentCredential(env);
36
- if (fromEnv !== undefined) {
37
- if (!validCredential(fromEnv))
38
- throw new CliError('missing_credentials', 'Supply a valid account key.', 3);
39
- return { key: fromEnv, source: 'env' };
40
- }
41
- const file = credentialPath(env);
42
- try {
43
- const info = await lstat(file), directory = await lstat(path.dirname(file));
44
- if (!info.isFile() || info.isSymbolicLink() || directory.isSymbolicLink() || (process.platform !== 'win32' && ((info.mode & 0o077) !== 0 || (directory.mode & 0o077) !== 0)))
45
- throw new Error('unsafe');
46
- const data = JSON.parse(await readFile(file, 'utf8'));
47
- if (!validCredential(data.developer_key))
48
- throw new Error('invalid');
49
- return { key: data.developer_key, source: 'stored' };
50
- }
51
- catch (error) {
52
- if (error.code === 'ENOENT')
53
- throw new CliError('missing_credentials', 'Ask the user to run croche login in their terminal.', 3);
54
- throw new CliError('invalid_credentials_file', 'Stored credentials are unreadable or insecure; the user should run croche login again.', 3);
55
- }
56
- }
57
- export async function storeCredential(env, key) {
58
- const file = credentialPath(env), directory = path.dirname(file);
59
- await mkdir(directory, { recursive: true, mode: 0o700 });
60
- if ((await lstat(directory)).isSymbolicLink())
61
- throw new CliError('invalid_configuration', 'Credential directory must not be a symbolic link.');
62
- if (process.platform !== 'win32')
63
- await chmod(directory, 0o700);
64
- const temporary = path.join(directory, `.credentials-${randomUUID()}.tmp`);
65
- let handle;
66
- try {
67
- handle = await open(temporary, 'wx', 0o600);
68
- await handle.writeFile(JSON.stringify({ developer_key: key }) + '\n');
69
- await handle.sync();
70
- await handle.close();
71
- handle = undefined;
72
- await rename(temporary, file);
73
- return file;
74
- }
75
- finally {
76
- try {
77
- await handle?.close();
78
- }
79
- finally {
80
- await unlink(temporary).catch(() => { });
81
- }
82
- }
83
- }
84
- export async function removeCredential(env) {
85
- try {
86
- await unlink(credentialPath(env));
87
- }
88
- catch (error) {
89
- if (error.code !== 'ENOENT')
90
- throw error;
91
- }
92
- }
93
- /** Human input only: never accept a credential in argv or echo its bytes. */
94
- export async function readCredentialInput(input = process.stdin, prompt = text => { process.stderr.write(text); }) {
95
- if (!input.isTTY) {
96
- let text = '';
97
- for await (const chunk of input) {
98
- text += chunk.toString();
99
- if (text.length > 512)
100
- throw new CliError('invalid_credentials', 'Credential input is too long.', 3);
101
- }
102
- return text.replace(/\r?\n$/, '');
103
- }
104
- prompt('Account key (hidden): ');
105
- const wasRaw = input.isRaw, wasFlowing = input.readableFlowing;
106
- return new Promise((resolve, reject) => {
107
- let text = '';
108
- const finish = (error) => { input.off('data', data); input.off('end', ended); input.setRawMode(wasRaw); if (wasFlowing !== true)
109
- input.pause(); prompt('\n'); error ? reject(error) : resolve(text); };
110
- const ended = () => finish(new CliError('invalid_credentials', 'Credential input ended unexpectedly.', 3));
111
- const data = (chunk) => {
112
- for (const char of chunk.toString()) {
113
- if (char === '\r' || char === '\n') {
114
- finish();
115
- return;
116
- }
117
- if (char === '\u0003') {
118
- finish(new CliError('cancelled', 'Login cancelled.', 2));
119
- return;
120
- }
121
- if (char === '\u007f' || char === '\b')
122
- text = text.slice(0, -1);
123
- else
124
- text += char;
125
- if (text.length > 259) {
126
- finish(new CliError('invalid_credentials', 'Credential input is too long.', 3));
127
- return;
128
- }
129
- }
130
- };
131
- input.setRawMode(true);
132
- input.on('data', data);
133
- input.once('end', ended);
134
- input.resume();
135
- });
136
- }
@@ -1,141 +0,0 @@
1
- import { appendFile, lstat, open, readFile, realpath, rename, unlink } from 'node:fs/promises';
2
- import { execFile } from 'node:child_process';
3
- import { promisify } from 'node:util';
4
- import { basename, dirname, relative, resolve, sep } from 'node:path';
5
- import { randomUUID } from 'node:crypto';
6
- import { CliError } from './index.js';
7
- const exec = promisify(execFile);
8
- const assignment = /^(?:export[ \t]+)?CROCHE_DEBUG_KEY[ \t]*=([^\r\n]*)(\r?)$/gm;
9
- const value = (line) => line.trim().replace(/^(['"])(.*)\1$/, '$2');
10
- async function git(root, args) {
11
- try {
12
- return (await exec('git', ['-C', root, ...args])).stdout.trim();
13
- }
14
- catch (error) {
15
- if (error.code === 'ENOENT')
16
- throw new CliError('git_unavailable', 'Git is required to protect the debug-key file.');
17
- return null;
18
- }
19
- }
20
- async function target(file, force, stderr) {
21
- const requested = resolve(file), parent = await realpath(dirname(requested)).catch(() => { throw new CliError('invalid_env_file', 'The env file directory must exist.'); });
22
- const path = resolve(parent, basename(requested));
23
- let before = null, mode = 0o600;
24
- try {
25
- const info = await lstat(path);
26
- if (!info.isFile() || info.isSymbolicLink())
27
- throw new CliError('invalid_env_file', 'The env file must be a regular file, not a symlink.');
28
- before = await readFile(path);
29
- mode = info.mode & 0o7777;
30
- }
31
- catch (error) {
32
- if (error.code !== 'ENOENT')
33
- throw error;
34
- }
35
- const root = await git(parent, ['rev-parse', '--show-toplevel']);
36
- let ignore;
37
- if (root) {
38
- const entry = relative(root, path).split(sep).join('/');
39
- if (await git(root, ['ls-files', '--error-unmatch', '--', entry]) !== null)
40
- throw new CliError('tracked_env_file', 'Refusing to write a debug key into a tracked file.');
41
- if (await git(root, ['check-ignore', '--', entry]) === null)
42
- ignore = { root, entry };
43
- }
44
- const existing = before ? [...before.toString('latin1').matchAll(assignment)] : [];
45
- if (existing.length > 1)
46
- throw new CliError('invalid_env_file', 'The env file contains multiple CROCHE_DEBUG_KEY assignments.');
47
- if (existing.some(match => value(match[1]) !== '') && !force)
48
- throw new CliError('debug_key_exists', 'CROCHE_DEBUG_KEY is already set; use --force to replace it. No key was issued.');
49
- if (before && (mode & 0o077))
50
- stderr('warning: the existing env file is group- or world-readable; its mode will be preserved.\n');
51
- return { path, before, mode, ignore };
52
- }
53
- /** Protect the destination before issuing any one-time credential. */
54
- async function ignoreFile(t) {
55
- if (!t.ignore)
56
- return;
57
- const path = resolve(t.ignore.root, '.gitignore');
58
- let before = '';
59
- try {
60
- before = await readFile(path, 'utf8');
61
- }
62
- catch (error) {
63
- if (error.code !== 'ENOENT')
64
- throw error;
65
- }
66
- // Root-anchored literal path: escape gitignore pattern metacharacters.
67
- const entry = '/' + t.ignore.entry.replace(/[\\*?\[\]#! ]/g, '\\$&');
68
- await appendFile(path, (before && !before.endsWith('\n') ? '\n' : '') + entry + '\n');
69
- }
70
- export async function writeDebugEnv(t, secret) {
71
- const text = t.before?.toString('latin1') ?? '';
72
- const matches = [...text.matchAll(assignment)];
73
- if (matches.length === 1 && value(matches[0][1]) === secret)
74
- return;
75
- const newline = text.includes('\r\n') ? '\r\n' : '\n';
76
- const updated = matches.length ? text.replace(assignment, (_line, _old, cr) => `CROCHE_DEBUG_KEY=${secret}${cr}`) : text + (text && !text.endsWith('\n') ? newline : '') + `CROCHE_DEBUG_KEY=${secret}${newline}`;
77
- const temporary = resolve(dirname(t.path), `.croche-debug-${randomUUID()}.tmp`);
78
- let handle;
79
- try {
80
- handle = await open(temporary, 'wx', 0o600);
81
- await handle.writeFile(Buffer.from(updated, 'latin1'));
82
- if (t.before)
83
- await handle.chmod(t.mode);
84
- await handle.sync();
85
- await handle.close();
86
- handle = undefined;
87
- let current = null;
88
- try {
89
- current = await readFile(t.path);
90
- }
91
- catch (error) {
92
- if (error.code !== 'ENOENT')
93
- throw error;
94
- }
95
- if (t.before === null ? current !== null : current === null || !current.equals(t.before))
96
- throw new Error('env file changed');
97
- await rename(temporary, t.path);
98
- }
99
- finally {
100
- try {
101
- await handle?.close();
102
- }
103
- finally {
104
- await unlink(temporary).catch(() => { });
105
- }
106
- }
107
- }
108
- export async function debugKeys(action, args, client) {
109
- const project = args.project;
110
- if (!project || !/^[A-Za-z0-9_.:-]{1,200}$/.test(project))
111
- throw new CliError('missing_argument', 'Supply --project with a project id.');
112
- const path = `/api/studio/projects/${encodeURIComponent(project)}/debug-tokens`;
113
- const metadata = (t) => ({ id: t.id, name: t.name, prefix: typeof t.prefix === 'string' ? t.prefix.slice(0, 12) : t.prefix, created_at: t.created_at, last_used_at: t.last_used_at, revoked_at: t.revoked_at, installations: t.installations, warning: t.warning });
114
- if (action === 'list') {
115
- const result = await client.request(path);
116
- return { debug_keys: result.debug_tokens.map(metadata) };
117
- }
118
- if (action === 'revoke') {
119
- if (!args['key-id'] || !/^[A-Za-z0-9_.:-]{1,200}$/.test(args['key-id']))
120
- throw new CliError('missing_argument', 'Supply a debug key id.');
121
- const result = await client.request(path + '/' + encodeURIComponent(args['key-id']), 'DELETE');
122
- return { debug_key: metadata(result.debug_token) };
123
- }
124
- const stderr = client.context.stderr ?? (text => process.stderr.write(text));
125
- const destination = args.print === 'true' && !args['env-file'] ? undefined : await target(args['env-file'] ?? './.env', args.force === 'true', stderr);
126
- if (destination)
127
- await ignoreFile(destination);
128
- const result = await client.request(path, 'POST', { name: args.name ?? 'Coding agent' });
129
- const key = metadata(result.debug_token);
130
- if (typeof result.secret !== 'string' || !/^cdt_[a-f0-9]{64}$/.test(result.secret))
131
- throw new CliError('invalid_response', `Cloud returned an invalid debug credential; revoke issued key ${key.id}.`, 1);
132
- if (destination) {
133
- try {
134
- await writeDebugEnv(destination, result.secret);
135
- }
136
- catch {
137
- throw new CliError('env_write_failed', `Could not safely write the env file. Revoke issued key ${key.id} with debug-keys revoke.`, 1, { key_id: key.id });
138
- }
139
- }
140
- return { debug_key: key, ...(destination ? { env_file: destination.path } : {}), ...(args.print === 'true' ? { secret: result.secret } : {}) };
141
- }