cueapril 0.0.0-stage → 1.2.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/io.mjs ADDED
@@ -0,0 +1,379 @@
1
+ // Shared process plumbing for the self-install commands (login, init, doctor).
2
+ // Every command takes an explicit deps object so tests can replace the network,
3
+ // the file system, the clock and child processes. defaultDeps() fills in the
4
+ // real implementations for anything a caller leaves out.
5
+ import * as nodeFs from 'node:fs/promises';
6
+ import { constants as fsConstants } from 'node:fs';
7
+ import { spawn as nodeSpawn } from 'node:child_process';
8
+ import { randomBytes as nodeRandomBytes } from 'node:crypto';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+
12
+ /**
13
+ * CLI exit codes. They mirror CLI_EXIT_CODES in
14
+ * apps/api/src/modules/quality-integrations/agent-contracts.ts, which is the
15
+ * published contract; keep the two in step.
16
+ */
17
+ export const EXIT = Object.freeze({
18
+ ok: 0,
19
+ failed: 1,
20
+ incomplete: 2,
21
+ blocked: 3,
22
+ timeout: 4,
23
+ error: 5,
24
+ });
25
+
26
+ /** An expected failure with a message that is safe to show and an exit code. */
27
+ export class CliError extends Error {
28
+ constructor(message, { exitCode = EXIT.error, code = 'error' } = {}) {
29
+ super(message);
30
+ this.name = 'CliError';
31
+ this.exitCode = exitCode;
32
+ this.code = code;
33
+ }
34
+ }
35
+
36
+ const RESOLVED = Symbol('cueapril.resolvedDeps');
37
+
38
+ /**
39
+ * Fills in real implementations for any dependency a caller leaves out.
40
+ * Already-resolved deps are returned as they are, so helpers can call this
41
+ * freely.
42
+ */
43
+ export function defaultDeps(overrides = {}) {
44
+ if (overrides && overrides[RESOLVED]) return overrides;
45
+ const defaults = {
46
+ fetch: (...args) => globalThis.fetch(...args),
47
+ env: process.env,
48
+ homedir: () => os.homedir(),
49
+ platform: process.platform,
50
+ stdout: process.stdout,
51
+ stderr: process.stderr,
52
+ stdin: process.stdin,
53
+ now: () => Date.now(),
54
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
55
+ spawn: nodeSpawn,
56
+ fs: nodeFs,
57
+ cwd: () => process.cwd(),
58
+ hostname: () => os.hostname(),
59
+ username: () => {
60
+ try {
61
+ return os.userInfo().username;
62
+ } catch {
63
+ return '';
64
+ }
65
+ },
66
+ randomBytes: nodeRandomBytes,
67
+ getuid: typeof process.getuid === 'function' ? () => process.getuid() : undefined,
68
+ };
69
+ const merged = { ...defaults };
70
+ for (const [name, value] of Object.entries(overrides ?? {})) {
71
+ if (value !== undefined) merged[name] = value;
72
+ }
73
+ Object.defineProperty(merged, RESOLVED, { value: true });
74
+ return merged;
75
+ }
76
+
77
+ export function homeDir(deps) {
78
+ const value = typeof deps.homedir === 'function' ? deps.homedir() : deps.homedir;
79
+ if (typeof value !== 'string' || !value) throw new CliError('Could not determine the home directory.');
80
+ return value;
81
+ }
82
+
83
+ export function currentDir(deps) {
84
+ const value = typeof deps.cwd === 'function' ? deps.cwd() : deps.cwd;
85
+ return typeof value === 'string' && value ? value : process.cwd();
86
+ }
87
+
88
+ /** Path functions for the target platform, so Windows paths can be tested on POSIX. */
89
+ export function pathFor(deps) {
90
+ return deps.platform === 'win32' ? path.win32 : path.posix;
91
+ }
92
+
93
+ export function isPosix(deps) {
94
+ return deps.platform !== 'win32';
95
+ }
96
+
97
+ export function isTTY(stream) {
98
+ return Boolean(stream && stream.isTTY);
99
+ }
100
+
101
+ export function writeLine(stream, text = '') {
102
+ if (stream && typeof stream.write === 'function') stream.write(`${text}\n`);
103
+ }
104
+
105
+ function relativeInside(p, parent, child) {
106
+ const relative = p.relative(parent, child);
107
+ const escapes = relative === '..' || relative.startsWith(`..${p.sep}`) || p.isAbsolute(relative);
108
+ return escapes ? null : relative;
109
+ }
110
+
111
+ /** Shows a path with the home directory as ~ so output stays short and private. */
112
+ export function displayPath(deps, target) {
113
+ try {
114
+ const p = pathFor(deps);
115
+ const relative = relativeInside(p, homeDir(deps), target);
116
+ if (relative === '') return '~';
117
+ if (relative !== null) return `~${p.sep}${relative}`;
118
+ } catch {
119
+ // fall through
120
+ }
121
+ return target;
122
+ }
123
+
124
+ export function isInside(deps, parent, child) {
125
+ return relativeInside(pathFor(deps), parent, child) !== null;
126
+ }
127
+
128
+ export async function readFileIfExists(deps, file) {
129
+ try {
130
+ return await defaultDeps(deps).fs.readFile(file, 'utf8');
131
+ } catch (error) {
132
+ if (error && error.code === 'ENOENT') return null;
133
+ throw error;
134
+ }
135
+ }
136
+
137
+ export async function lstatIfExists(deps, file) {
138
+ try {
139
+ return await defaultDeps(deps).fs.lstat(file);
140
+ } catch (error) {
141
+ if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return null;
142
+ throw error;
143
+ }
144
+ }
145
+
146
+ export async function exists(deps, file) {
147
+ return (await lstatIfExists(deps, file)) !== null;
148
+ }
149
+
150
+ /**
151
+ * Writes a file atomically: a private temporary file in the same directory is
152
+ * written, flushed and renamed over the target, so a reader never sees half a
153
+ * file and the target never exists with wider permissions than `mode`.
154
+ */
155
+ export async function atomicWriteFile(rawDeps, file, content, { mode = 0o600, dirMode = 0o700 } = {}) {
156
+ const deps = defaultDeps(rawDeps);
157
+ const p = pathFor(deps);
158
+ const dir = p.dirname(file);
159
+ await deps.fs.mkdir(dir, { recursive: true, mode: dirMode });
160
+ const suffix = deps.randomBytes(6).toString('hex');
161
+ const temporary = p.join(dir, `.${p.basename(file)}.${suffix}.tmp`);
162
+ let handle;
163
+ try {
164
+ handle = await deps.fs.open(temporary, 'wx', mode);
165
+ await handle.writeFile(content, 'utf8');
166
+ if (typeof handle.sync === 'function') await handle.sync();
167
+ await handle.close();
168
+ handle = undefined;
169
+ if (isPosix(deps)) await deps.fs.chmod(temporary, mode);
170
+ await deps.fs.rename(temporary, file);
171
+ } catch (error) {
172
+ if (handle) await handle.close().catch(() => {});
173
+ await deps.fs.rm(temporary, { force: true }).catch(() => {});
174
+ throw error;
175
+ }
176
+ if (isPosix(deps)) await deps.fs.chmod(file, mode);
177
+ }
178
+
179
+ /** The root of the git repository that contains `start`, or null. */
180
+ export async function findRepositoryRoot(rawDeps, start) {
181
+ const deps = defaultDeps(rawDeps);
182
+ const p = pathFor(deps);
183
+ let dir = p.resolve(start ?? currentDir(deps));
184
+ for (;;) {
185
+ if (await exists(deps, p.join(dir, '.git'))) return dir;
186
+ const parent = p.dirname(dir);
187
+ if (parent === dir) return null;
188
+ dir = parent;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Where `target` would really be written: the deepest ancestor that exists is
194
+ * resolved with realpath, so every symbolic link on the way is followed, and
195
+ * the parts still to be created are added back. Null when no ancestor exists.
196
+ */
197
+ export async function realTargetPath(rawDeps, target) {
198
+ const deps = defaultDeps(rawDeps);
199
+ const p = pathFor(deps);
200
+ const pending = [p.basename(target)];
201
+ let dir = p.dirname(p.resolve(target));
202
+ for (;;) {
203
+ try {
204
+ return p.join(await deps.fs.realpath(dir), ...pending);
205
+ } catch (error) {
206
+ if (!error || (error.code !== 'ENOENT' && error.code !== 'ENOTDIR')) throw error;
207
+ }
208
+ const parent = p.dirname(dir);
209
+ if (parent === dir) return null;
210
+ pending.unshift(p.basename(dir));
211
+ dir = parent;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Refuses to write a key-bearing file inside a git work tree, so a key can
217
+ * never be committed by accident: the repository the command runs in (on the
218
+ * path as given), and any repository the file's real location is in once
219
+ * symbolic links are followed, for example a ~/.config that links into a
220
+ * dotfiles repository. A home directory that is itself a repository is
221
+ * allowed: user configuration lives there.
222
+ */
223
+ export async function assertOutsideRepository(rawDeps, target, what = 'a CueApril key', { hint = '' } = {}) {
224
+ const deps = defaultDeps(rawDeps);
225
+ const home = homeDir(deps);
226
+ const p = pathFor(deps);
227
+ const refuse = (where, root) => {
228
+ throw new CliError(
229
+ `Refusing to write ${what} to ${target}: ${where} inside the repository at ${root}. ` +
230
+ `Keys are only stored in user-level configuration.${hint ? ` ${hint}` : ''}`,
231
+ );
232
+ };
233
+ const root = await findRepositoryRoot(deps);
234
+ if (root && p.resolve(root) !== p.resolve(home) && isInside(deps, root, target)) refuse('it is', root);
235
+ const real = await realTargetPath(deps, target);
236
+ if (!real) return;
237
+ const realRoot = await findRepositoryRoot(deps, p.dirname(real));
238
+ if (!realRoot) return;
239
+ const realHome = await deps.fs.realpath(home).catch(() => home);
240
+ if (p.resolve(realRoot) === p.resolve(realHome) || p.resolve(realRoot) === p.resolve(home)) return;
241
+ refuse(p.resolve(real) === p.resolve(target) ? 'it is' : `a symbolic link on the way leads to ${real}, which is`, realRoot);
242
+ }
243
+
244
+ /**
245
+ * Runs a command with an argument array and no shell, capturing bounded
246
+ * output. It never throws: spawn failures come back as `error`.
247
+ */
248
+ export function runCommand(rawDeps, command, args, { timeoutMs = 60_000, maxOutput = 1_000_000 } = {}) {
249
+ const deps = defaultDeps(rawDeps);
250
+ return new Promise((resolve) => {
251
+ let child;
252
+ try {
253
+ child = deps.spawn(command, args, {
254
+ shell: false,
255
+ stdio: ['ignore', 'pipe', 'pipe'],
256
+ windowsHide: true,
257
+ env: deps.env,
258
+ });
259
+ } catch (error) {
260
+ resolve({ code: null, stdout: '', stderr: '', error });
261
+ return;
262
+ }
263
+ let stdout = '';
264
+ let stderr = '';
265
+ let settled = false;
266
+ const finish = (result) => {
267
+ if (settled) return;
268
+ settled = true;
269
+ clearTimeout(timer);
270
+ resolve({ code: null, stdout, stderr, ...result });
271
+ };
272
+ const timer = setTimeout(() => {
273
+ try {
274
+ child.kill('SIGTERM');
275
+ } catch {
276
+ // already gone
277
+ }
278
+ finish({ timedOut: true, error: new Error(`${path.basename(command)} did not finish in time`) });
279
+ }, timeoutMs);
280
+ if (typeof timer.unref === 'function') timer.unref();
281
+ child.stdout?.on('data', (chunk) => {
282
+ if (stdout.length < maxOutput) stdout += String(chunk);
283
+ });
284
+ child.stderr?.on('data', (chunk) => {
285
+ if (stderr.length < maxOutput) stderr += String(chunk);
286
+ });
287
+ child.on('error', (error) => finish({ error }));
288
+ child.on('close', (code) => finish({ code }));
289
+ });
290
+ }
291
+
292
+ /**
293
+ * Finds an executable on PATH. Relative PATH entries, node_modules/.bin
294
+ * directories and directories inside the current repository are skipped, so a
295
+ * repository cannot plant a binary that receives a key on its command line.
296
+ */
297
+ export async function which(rawDeps, name) {
298
+ const deps = defaultDeps(rawDeps);
299
+ const p = pathFor(deps);
300
+ const windows = deps.platform === 'win32';
301
+ const raw = deps.env.PATH ?? deps.env.Path ?? '';
302
+ const dirs = String(raw)
303
+ .split(windows ? ';' : ':')
304
+ .filter(Boolean);
305
+ const extensions = windows
306
+ ? String(deps.env.PATHEXT || '.EXE;.CMD;.BAT;.COM')
307
+ .split(';')
308
+ .filter(Boolean)
309
+ .map((ext) => ext.toLowerCase())
310
+ : [''];
311
+ const repository = await findRepositoryRoot(deps).catch(() => null);
312
+ const home = homeDir(deps);
313
+ for (const dir of dirs) {
314
+ if (!p.isAbsolute(dir)) continue;
315
+ if (dir.split(/[\\/]/).includes('node_modules')) continue;
316
+ if (repository && p.resolve(repository) !== p.resolve(home) && isInside(deps, repository, dir)) continue;
317
+ for (const extension of extensions) {
318
+ const candidate = p.join(dir, name + extension);
319
+ if (await isExecutable(deps, candidate)) return candidate;
320
+ }
321
+ }
322
+ return null;
323
+ }
324
+
325
+ export async function isExecutable(rawDeps, file) {
326
+ const deps = defaultDeps(rawDeps);
327
+ try {
328
+ const stat = await deps.fs.stat(file);
329
+ if (!stat.isFile()) return false;
330
+ if (deps.platform === 'win32') return true;
331
+ await deps.fs.access(file, fsConstants.X_OK);
332
+ return true;
333
+ } catch {
334
+ return false;
335
+ }
336
+ }
337
+
338
+ /** Removes anything that looks like a CueApril key, plus any listed secret. */
339
+ export function redact(text, secrets = []) {
340
+ let value = String(text ?? '');
341
+ for (const secret of secrets) {
342
+ if (typeof secret === 'string' && secret.length >= 8) value = value.split(secret).join('[redacted]');
343
+ }
344
+ return value.replace(/cueapril_sk_[A-Za-z0-9_-]+/g, 'cueapril_sk_[redacted]');
345
+ }
346
+
347
+ /** A UTF-8 byte order mark, written by code point so it stays visible in source. */
348
+ export const BOM = String.fromCharCode(0xfeff);
349
+
350
+ function codePointRange([from, to]) {
351
+ const hex = (point) => `\\u${point.toString(16).padStart(4, '0')}`;
352
+ return `${hex(from)}-${hex(to)}`;
353
+ }
354
+
355
+ // Control characters, zero-width characters, line separators and bidirectional
356
+ // overrides: anything that could hide or reorder text in a terminal.
357
+ const INVISIBLE = new RegExp(
358
+ `[${[
359
+ [0x0000, 0x001f],
360
+ [0x007f, 0x009f],
361
+ [0x200b, 0x200f],
362
+ [0x2028, 0x202e],
363
+ [0x2066, 0x2069],
364
+ [0xfeff, 0xfeff],
365
+ ]
366
+ .map(codePointRange)
367
+ .join('')}]+`,
368
+ 'g',
369
+ );
370
+
371
+ /** Single-line, printable, bounded text from an untrusted source. */
372
+ export function safeText(value, max = 300) {
373
+ if (value === undefined || value === null) return '';
374
+ const text = String(value)
375
+ .replace(INVISIBLE, ' ')
376
+ .replace(/\s+/g, ' ')
377
+ .trim();
378
+ return text.length > max ? `${text.slice(0, max - 3)}...` : text;
379
+ }
package/key-store.mjs ADDED
@@ -0,0 +1,287 @@
1
+ // Local storage for CueApril agent keys.
2
+ //
3
+ // File: $XDG_CONFIG_HOME/cueapril/credentials.json, else
4
+ // ~/.config/cueapril/credentials.json (Windows: %APPDATA%\cueapril\credentials.json).
5
+ // The directory is 0700 and the file 0600; it is replaced atomically and keyed
6
+ // by canonical base URL, so one machine can hold keys for several servers.
7
+ // Key precedence: CUEAPRIL_API_KEY, then TENHAW_TOKEN, then the stored key.
8
+ import {
9
+ CliError,
10
+ assertOutsideRepository,
11
+ atomicWriteFile,
12
+ defaultDeps,
13
+ homeDir,
14
+ isPosix,
15
+ isTTY,
16
+ pathFor,
17
+ safeText,
18
+ } from './io.mjs';
19
+ import { isHeaderSafeToken, normaliseBaseUrl, resolveBaseUrl } from './http.mjs';
20
+
21
+ /** cueapril_sk_<20 hex>_<43 base64url>, as issued by CueApril. */
22
+ export const AGENT_KEY_PATTERN = /^cueapril_sk_[0-9a-f]{20}_[A-Za-z0-9_-]{43}$/;
23
+ export const CREDENTIALS_FILE = 'credentials.json';
24
+ const FILE_VERSION = 1;
25
+ const MAX_FILE_BYTES = 1_000_000;
26
+
27
+ /** Read an explicitly supplied key without ever echoing it or taking it in argv. */
28
+ export async function readApiKeyStdin(deps = {}) {
29
+ const io = defaultDeps(deps);
30
+ if (isTTY(io.stdin)) {
31
+ throw new CredentialsError('--key-stdin needs a pipe, not a terminal. Supply the key through a secret manager or set CUEAPRIL_API_KEY; never paste it into chat.');
32
+ }
33
+ if (typeof io.stdin?.on !== 'function' || io.stdin.readableEnded || io.stdin.destroyed) {
34
+ throw new CredentialsError('--key-stdin needs a readable pipe containing one CueApril agent key.');
35
+ }
36
+ return new Promise((resolve, reject) => {
37
+ let input = '';
38
+ let settled = false;
39
+ const finish = (error) => {
40
+ if (settled) return;
41
+ settled = true;
42
+ clearTimeout(timer);
43
+ io.stdin.removeListener('data', onData);
44
+ io.stdin.removeListener('end', onEnd);
45
+ io.stdin.removeListener('error', onError);
46
+ io.stdin.pause?.();
47
+ if (error) return reject(error);
48
+ const key = input.trim();
49
+ if (!AGENT_KEY_PATTERN.test(key)) return reject(new CredentialsError('Standard input must contain exactly one complete CueApril agent key. Nothing was saved.'));
50
+ resolve(key);
51
+ };
52
+ const onData = (chunk) => {
53
+ input += String(chunk);
54
+ if (Buffer.byteLength(input, 'utf8') > 1024) finish(new CredentialsError('The --key-stdin input exceeds 1024 bytes. Nothing was saved.'));
55
+ };
56
+ const onEnd = () => finish();
57
+ const onError = () => finish(new CredentialsError('Could not read the key from standard input. Nothing was saved.'));
58
+ const timer = setTimeout(() => finish(new CredentialsError('No complete key arrived on standard input within 10 seconds. Nothing was saved.')), 10_000);
59
+ io.stdin.on('data', onData);
60
+ io.stdin.once('end', onEnd);
61
+ io.stdin.once('error', onError);
62
+ io.stdin.resume?.();
63
+ });
64
+ }
65
+
66
+ export class CredentialsError extends CliError {
67
+ constructor(message) {
68
+ super(message, { code: 'credentials' });
69
+ this.name = 'CredentialsError';
70
+ }
71
+ }
72
+
73
+ export function configDir(deps = {}) {
74
+ const resolved = defaultDeps(deps);
75
+ const p = pathFor(resolved);
76
+ const env = resolved.env;
77
+ if (resolved.platform === 'win32') {
78
+ const appData =
79
+ typeof env.APPDATA === 'string' && env.APPDATA ? env.APPDATA : p.join(homeDir(resolved), 'AppData', 'Roaming');
80
+ return p.join(appData, 'cueapril');
81
+ }
82
+ const xdg = typeof env.XDG_CONFIG_HOME === 'string' && env.XDG_CONFIG_HOME.trim() ? env.XDG_CONFIG_HOME.trim() : '';
83
+ // The XDG spec says relative values are invalid and must be ignored.
84
+ if (xdg && p.isAbsolute(xdg)) return p.join(xdg, 'cueapril');
85
+ return p.join(homeDir(resolved), '.config', 'cueapril');
86
+ }
87
+
88
+ export function credentialsPath(deps = {}) {
89
+ return pathFor(defaultDeps(deps)).join(configDir(deps), CREDENTIALS_FILE);
90
+ }
91
+
92
+ /**
93
+ * Refuses to write a key-bearing file in the CueApril configuration directory
94
+ * when it, or the real location a symbolic link gives it, is in a git work tree.
95
+ */
96
+ export async function assertPrivateConfigFile(deps, file, what = 'a CueApril key') {
97
+ const resolved = defaultDeps(deps);
98
+ const hint = isPosix(resolved) ? 'Set XDG_CONFIG_HOME to a directory outside any repository.' : '';
99
+ await assertOutsideRepository(resolved, file, what, { hint });
100
+ }
101
+
102
+ /** Masks a key for display: the prefix and the first characters of its id only. */
103
+ export function maskKey(key) {
104
+ if (typeof key !== 'string' || !key) return '(none)';
105
+ const agent = /^cueapril_sk_([0-9a-f]{20})_/.exec(key);
106
+ if (agent) return `cueapril_sk_${agent[1].slice(0, 8)}...`;
107
+ return `${key.slice(0, 4)}... (${key.length} characters)`;
108
+ }
109
+
110
+ function modeText(mode) {
111
+ return `0${(mode & 0o777).toString(8)}`;
112
+ }
113
+
114
+ /**
115
+ * Checks, on POSIX, that a private file is owned by this user and not
116
+ * accessible to anyone else, and that its directory cannot be written by others.
117
+ */
118
+ export async function assertPrivateFile(deps, file, label = 'credentials file') {
119
+ if (!isPosix(deps)) return;
120
+ const p = pathFor(deps);
121
+ const stat = await deps.fs.stat(file);
122
+ const uid = typeof deps.getuid === 'function' ? deps.getuid() : undefined;
123
+ if (uid !== undefined && typeof stat.uid === 'number' && stat.uid !== uid) {
124
+ throw new CredentialsError(
125
+ `The ${label} ${file} belongs to another user. Remove it, then run \`cueapril login\` again.`,
126
+ );
127
+ }
128
+ if ((stat.mode & 0o077) !== 0) {
129
+ throw new CredentialsError(
130
+ `The ${label} ${file} can be read by other users (mode ${modeText(stat.mode)}). ` +
131
+ `Fix it with: chmod 600 "${file}"`,
132
+ );
133
+ }
134
+ const dir = p.dirname(file);
135
+ const dirStat = await deps.fs.stat(dir);
136
+ if ((dirStat.mode & 0o022) !== 0) {
137
+ throw new CredentialsError(
138
+ `The directory ${dir} can be changed by other users (mode ${modeText(dirStat.mode)}). ` +
139
+ `Fix it with: chmod 700 "${dir}"`,
140
+ );
141
+ }
142
+ }
143
+
144
+ function emptyStore() {
145
+ return { version: FILE_VERSION, credentials: {} };
146
+ }
147
+
148
+ async function readStore(deps, { forWrite = false } = {}) {
149
+ const file = credentialsPath(deps);
150
+ let text;
151
+ try {
152
+ const stat = await deps.fs.stat(file);
153
+ if (stat.size > MAX_FILE_BYTES) throw new CredentialsError(`The credentials file ${file} is too large to be valid.`);
154
+ if (!forWrite) await assertPrivateFile(deps, file);
155
+ else if (isPosix(deps) && typeof deps.getuid === 'function' && stat.uid !== deps.getuid()) {
156
+ throw new CredentialsError(`The credentials file ${file} belongs to another user. Remove it first.`);
157
+ }
158
+ text = await deps.fs.readFile(file, 'utf8');
159
+ } catch (error) {
160
+ if (error && error.code === 'ENOENT') return { file, store: emptyStore(), existed: false };
161
+ throw error;
162
+ }
163
+ let parsed;
164
+ try {
165
+ parsed = JSON.parse(text);
166
+ } catch {
167
+ throw new CredentialsError(
168
+ `The credentials file ${file} is not valid JSON. Move it aside or delete it, then run \`cueapril login\`.`,
169
+ );
170
+ }
171
+ const credentials = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed.credentials : null;
172
+ if (!credentials || typeof credentials !== 'object' || Array.isArray(credentials)) {
173
+ throw new CredentialsError(
174
+ `The credentials file ${file} has an unexpected shape. Move it aside or delete it, then run \`cueapril login\`.`,
175
+ );
176
+ }
177
+ return { file, store: { version: FILE_VERSION, credentials: { ...credentials } }, existed: true };
178
+ }
179
+
180
+ function stringList(value, max = 100) {
181
+ if (!Array.isArray(value)) return undefined;
182
+ return value
183
+ .filter((item) => typeof item === 'string' && item.trim())
184
+ .slice(0, max)
185
+ .map((item) => safeText(item, 200));
186
+ }
187
+
188
+ /** Keeps only known, bounded metadata fields from a server response. */
189
+ export function sanitiseCredentialRecord(record) {
190
+ const out = {};
191
+ for (const field of ['id', 'key_prefix', 'name', 'organisation_id', 'organisation_name', 'expires_at', 'saved_at']) {
192
+ if (typeof record?.[field] === 'string' && record[field].trim()) out[field] = safeText(record[field], 200);
193
+ }
194
+ for (const field of ['project_ids', 'scopes', 'environment_ids']) {
195
+ const list = stringList(record?.[field]);
196
+ if (list) out[field] = list;
197
+ }
198
+ return out;
199
+ }
200
+
201
+ /** The stored credential for a base URL, or null. Throws CredentialsError on an unsafe file. */
202
+ export async function readCredential(baseUrl, deps = {}) {
203
+ const resolved = defaultDeps(deps);
204
+ const key = normaliseBaseUrl(baseUrl);
205
+ const { store } = await readStore(resolved);
206
+ const entry = store.credentials[key];
207
+ if (!entry || typeof entry !== 'object') return null;
208
+ if (!isHeaderSafeToken(entry.key)) {
209
+ throw new CredentialsError(`The stored key for ${key} is malformed. Run \`cueapril login\` to replace it.`);
210
+ }
211
+ return { ...sanitiseCredentialRecord(entry), key: entry.key };
212
+ }
213
+
214
+ /**
215
+ * Stores an agent key for a base URL, keeping keys for other servers. The key
216
+ * must be a CueApril agent key; metadata is filtered to known fields.
217
+ */
218
+ export async function writeCredential(baseUrl, record, deps = {}) {
219
+ const resolved = defaultDeps(deps);
220
+ const url = normaliseBaseUrl(baseUrl);
221
+ if (!record || typeof record.key !== 'string' || !AGENT_KEY_PATTERN.test(record.key)) {
222
+ throw new CredentialsError('Refusing to store a value that is not a CueApril agent key.');
223
+ }
224
+ const file = credentialsPath(resolved);
225
+ await assertPrivateConfigFile(resolved, file);
226
+ const { store } = await readStore(resolved, { forWrite: true });
227
+ store.credentials[url] = {
228
+ ...sanitiseCredentialRecord(record),
229
+ key: record.key,
230
+ saved_at: new Date(resolved.now()).toISOString(),
231
+ };
232
+ await atomicWriteFile(resolved, file, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
233
+ if (isPosix(resolved)) await resolved.fs.chmod(pathFor(resolved).dirname(file), 0o700);
234
+ return { path: file };
235
+ }
236
+
237
+ /** Removes the stored key for a base URL; deletes the file when it holds no keys. */
238
+ export async function deleteCredential(baseUrl, deps = {}) {
239
+ const resolved = defaultDeps(deps);
240
+ const url = normaliseBaseUrl(baseUrl);
241
+ const { file, store, existed } = await readStore(resolved, { forWrite: true });
242
+ if (!existed || !(url in store.credentials)) return { deleted: false, path: file };
243
+ delete store.credentials[url];
244
+ if (Object.keys(store.credentials).length === 0) await resolved.fs.rm(file, { force: true });
245
+ else await atomicWriteFile(resolved, file, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
246
+ return { deleted: true, path: file };
247
+ }
248
+
249
+ function envKey(env, name) {
250
+ const value = env[name];
251
+ if (typeof value !== 'string' || !value.trim()) return null;
252
+ const key = value.trim();
253
+ if (!isHeaderSafeToken(key)) {
254
+ throw new CredentialsError(`${name} is set but is not a usable key (it contains spaces or other invalid characters).`);
255
+ }
256
+ if (key.startsWith('cueapril_sk_') && !AGENT_KEY_PATTERN.test(key)) {
257
+ throw new CredentialsError(`${name} starts with cueapril_sk_ but is not a complete agent key; copy the whole key.`);
258
+ }
259
+ return key;
260
+ }
261
+
262
+ /**
263
+ * Resolves the key to use: CUEAPRIL_API_KEY, then TENHAW_TOKEN, then the key
264
+ * stored for the base URL. Returns null when there is none.
265
+ * Result: { key, source: 'env', envName, baseUrl } or
266
+ * { key, source: 'store', path, record, baseUrl }.
267
+ * The caller must never print `key`; use maskKey() and describeKeySource().
268
+ */
269
+ export async function resolveApiKey(deps = {}, { baseUrl } = {}) {
270
+ const resolved = defaultDeps(deps);
271
+ const url = baseUrl ? normaliseBaseUrl(baseUrl) : resolveBaseUrl(resolved.env);
272
+ for (const envName of ['CUEAPRIL_API_KEY', 'TENHAW_TOKEN']) {
273
+ const key = envKey(resolved.env, envName);
274
+ if (key) return { key, source: 'env', envName, baseUrl: url };
275
+ }
276
+ const stored = await readCredential(url, resolved);
277
+ if (!stored) return null;
278
+ const { key, ...record } = stored;
279
+ return { key, source: 'store', path: credentialsPath(resolved), record, baseUrl: url };
280
+ }
281
+
282
+ /** Human description of where a resolved key came from, without the key. */
283
+ export function describeKeySource(resolvedKey, display = (value) => value) {
284
+ if (!resolvedKey) return 'none';
285
+ if (resolvedKey.source === 'env') return `the ${resolvedKey.envName} environment variable`;
286
+ return display(resolvedKey.path);
287
+ }