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/README.md +173 -2
- package/agents.mjs +996 -0
- package/cli.mjs +4 -0
- package/client.mjs +360 -0
- package/commands.mjs +1273 -0
- package/doctor.mjs +186 -0
- package/http.mjs +263 -0
- package/init.mjs +635 -0
- package/io.mjs +379 -0
- package/key-store.mjs +287 -0
- package/login.mjs +601 -0
- package/package.json +39 -4
- package/skill/cueapril-qa/SKILL.md +90 -0
package/login.mjs
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
// cueapril login: device approval without copying a key.
|
|
2
|
+
//
|
|
3
|
+
// The CLI makes a random device secret, shows a link and a short code, and
|
|
4
|
+
// polls until an organisation owner or admin approves the request in the
|
|
5
|
+
// browser. The server then returns a new agent key exactly once; the CLI
|
|
6
|
+
// stores it in the credentials file and never prints it unless asked.
|
|
7
|
+
//
|
|
8
|
+
// device_secret = 32 random bytes, base64url (43 characters)
|
|
9
|
+
// request_id = hex SHA-256 of device_secret
|
|
10
|
+
// code = first 8 hex characters of request_id, upper case, XXXX-XXXX
|
|
11
|
+
//
|
|
12
|
+
// The pending request is saved (0600) next to the credentials, so running
|
|
13
|
+
// `cueapril login` or `cueapril init` again resumes the same link and code,
|
|
14
|
+
// for example after an agent's shell timeout killed the first attempt.
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
import { parseArgs } from 'node:util';
|
|
17
|
+
import {
|
|
18
|
+
CliError,
|
|
19
|
+
EXIT,
|
|
20
|
+
atomicWriteFile,
|
|
21
|
+
defaultDeps,
|
|
22
|
+
displayPath,
|
|
23
|
+
isTTY,
|
|
24
|
+
pathFor,
|
|
25
|
+
redact,
|
|
26
|
+
safeText,
|
|
27
|
+
writeLine,
|
|
28
|
+
} from './io.mjs';
|
|
29
|
+
import { HttpError, createHttpClient, resolveBaseUrl } from './http.mjs';
|
|
30
|
+
import {
|
|
31
|
+
AGENT_KEY_PATTERN,
|
|
32
|
+
assertPrivateConfigFile,
|
|
33
|
+
assertPrivateFile,
|
|
34
|
+
configDir,
|
|
35
|
+
deleteCredential,
|
|
36
|
+
maskKey,
|
|
37
|
+
readCredential,
|
|
38
|
+
readApiKeyStdin,
|
|
39
|
+
sanitiseCredentialRecord,
|
|
40
|
+
writeCredential,
|
|
41
|
+
} from './key-store.mjs';
|
|
42
|
+
|
|
43
|
+
export const CLAIM_PATH = '/api/v1/quality/agent-auth/device/claim';
|
|
44
|
+
export const SELF_REVOKE_PATH = '/api/v1/quality/agent-auth/key';
|
|
45
|
+
export const CONNECT_PATH = '/agents/connect';
|
|
46
|
+
export const POLL_INTERVAL_MS = 5_000;
|
|
47
|
+
export const HEARTBEAT_INTERVAL_MS = 30_000;
|
|
48
|
+
export const DEFAULT_TIMEOUT_MINUTES = 10;
|
|
49
|
+
export const MAX_TIMEOUT_MINUTES = 60;
|
|
50
|
+
/** How long a saved, unapproved request may be resumed. */
|
|
51
|
+
export const PENDING_TTL_MS = 30 * 60_000;
|
|
52
|
+
const PENDING_FILE = 'pending-login.json';
|
|
53
|
+
const DEVICE_SECRET = /^[A-Za-z0-9_-]{43}$/;
|
|
54
|
+
const REQUEST_ID = /^[0-9a-f]{64}$/;
|
|
55
|
+
|
|
56
|
+
export const LOGIN_USAGE = `Usage: cueapril login [--name <label>] [--no-browser] [--print-key] [--timeout <minutes>] [--no-wait] [--new] [--json]
|
|
57
|
+
cueapril login --key-stdin [--json]
|
|
58
|
+
|
|
59
|
+
Connects this computer to CueApril. Open the link it prints, check the code,
|
|
60
|
+
and approve (an organisation owner or admin must approve). The key is saved in
|
|
61
|
+
your user configuration and is never printed unless you pass --print-key.
|
|
62
|
+
|
|
63
|
+
--name <label> Name shown on the approval page and in Settings
|
|
64
|
+
--no-browser Do not open a browser; just print the link
|
|
65
|
+
--print-key Also print the key (for CI secrets); handle it carefully
|
|
66
|
+
--timeout <min> How long to wait for approval (default 10, maximum 60)
|
|
67
|
+
--no-wait Print the link and exit; run login or init again to finish
|
|
68
|
+
--new Discard a pending request and start a new one
|
|
69
|
+
--json Print machine-readable JSON lines on stdout
|
|
70
|
+
--key-stdin Verify and store an existing agent key from a pipe; never argv or chat
|
|
71
|
+
|
|
72
|
+
Exit codes: 0 approved, 4 timed out, 5 error.`;
|
|
73
|
+
|
|
74
|
+
export const LOGOUT_USAGE = `Usage: cueapril logout [--local] [--json]
|
|
75
|
+
|
|
76
|
+
Revokes the stored key on the server and deletes it from this computer.
|
|
77
|
+
--local Only delete the local copy; do not revoke it on the server`;
|
|
78
|
+
|
|
79
|
+
/** Creates the device secret, the request id the browser sees and the code to compare. */
|
|
80
|
+
export function createDeviceRequest(randomBytes) {
|
|
81
|
+
const deviceSecret = Buffer.from(randomBytes(32)).toString('base64url');
|
|
82
|
+
return { deviceSecret, ...deriveRequest(deviceSecret) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function deriveRequest(deviceSecret) {
|
|
86
|
+
const requestId = createHash('sha256').update(deviceSecret, 'utf8').digest('hex');
|
|
87
|
+
const code = requestId.slice(0, 8).toUpperCase();
|
|
88
|
+
return { requestId, code: `${code.slice(0, 4)}-${code.slice(4)}` };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function verificationUrl(baseUrl, requestId, name) {
|
|
92
|
+
return `${baseUrl}${CONNECT_PATH}?${new URLSearchParams({ request: requestId, name })}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function slug(value) {
|
|
96
|
+
return String(value ?? '')
|
|
97
|
+
.replace(/[^A-Za-z0-9._-]+/g, '-')
|
|
98
|
+
.replace(/^-+|-+$/g, '')
|
|
99
|
+
.slice(0, 40);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Which coding agent (if any) is running this command, from the markers each sets. */
|
|
103
|
+
export function detectRunningAgent(env = {}) {
|
|
104
|
+
if (env.CLAUDECODE === '1' || env.CLAUDE_CODE_ENTRYPOINT) return 'claude-code';
|
|
105
|
+
if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED || env.CODEX_THREAD_ID) return 'codex';
|
|
106
|
+
if (env.GEMINI_CLI === '1') return 'gemini-cli';
|
|
107
|
+
if (env.CURSOR_AGENT) return 'cursor';
|
|
108
|
+
return '';
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* "<agent> <date>", for example "claude-code 2026-11-15". The label travels in
|
|
113
|
+
* the approval page's address, which the web app's analytics can see, so it
|
|
114
|
+
* never includes the user name or host name; --name overrides it.
|
|
115
|
+
*/
|
|
116
|
+
export function defaultKeyLabel(deps) {
|
|
117
|
+
const who = detectRunningAgent(deps.env) || 'cueapril-cli';
|
|
118
|
+
const now = typeof deps.now === 'function' ? safeCall(deps.now) : Date.now();
|
|
119
|
+
const day = new Date(Number.isFinite(now) ? now : Date.now()).toISOString().slice(0, 10);
|
|
120
|
+
return `${who} ${day}`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function safeCall(fn) {
|
|
124
|
+
try {
|
|
125
|
+
return typeof fn === 'function' ? fn() : fn;
|
|
126
|
+
} catch {
|
|
127
|
+
return '';
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function parseTimeoutMinutes(raw) {
|
|
132
|
+
if (raw === undefined) return DEFAULT_TIMEOUT_MINUTES;
|
|
133
|
+
const value = Number(raw);
|
|
134
|
+
if (!/^\d+(\.\d+)?$/.test(String(raw).trim()) || !Number.isFinite(value) || value <= 0 || value > MAX_TIMEOUT_MINUTES) {
|
|
135
|
+
throw new CliError(`--timeout must be a number of minutes between 0 and ${MAX_TIMEOUT_MINUTES}.`);
|
|
136
|
+
}
|
|
137
|
+
return value;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function parseLabel(raw) {
|
|
141
|
+
const label = safeText(raw, 80);
|
|
142
|
+
if (!label) throw new CliError('--name must not be empty.');
|
|
143
|
+
return label;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function pendingPath(deps) {
|
|
147
|
+
return pathFor(deps).join(configDir(deps), PENDING_FILE);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function readPendingStore(deps) {
|
|
151
|
+
const file = pendingPath(deps);
|
|
152
|
+
try {
|
|
153
|
+
await assertPrivateFile(deps, file, 'pending login file');
|
|
154
|
+
const parsed = JSON.parse(await deps.fs.readFile(file, 'utf8'));
|
|
155
|
+
if (parsed && typeof parsed === 'object' && parsed.requests && typeof parsed.requests === 'object') {
|
|
156
|
+
return { version: 1, requests: { ...parsed.requests } };
|
|
157
|
+
}
|
|
158
|
+
} catch {
|
|
159
|
+
// Missing, unreadable, unsafe or malformed: start again with a fresh request.
|
|
160
|
+
}
|
|
161
|
+
return { version: 1, requests: {} };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A resumable request for this base URL, or null when there is none or it is stale. */
|
|
165
|
+
export async function readPendingLogin(baseUrl, deps) {
|
|
166
|
+
const store = await readPendingStore(deps);
|
|
167
|
+
const entry = store.requests[baseUrl];
|
|
168
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
169
|
+
const { device_secret: deviceSecret, name, created_at: createdAt } = entry;
|
|
170
|
+
if (typeof deviceSecret !== 'string' || !DEVICE_SECRET.test(deviceSecret)) return null;
|
|
171
|
+
const created = Date.parse(createdAt);
|
|
172
|
+
const age = deps.now() - created;
|
|
173
|
+
if (!Number.isFinite(created) || age < -60_000 || age > PENDING_TTL_MS) return null;
|
|
174
|
+
const label = typeof name === 'string' ? safeText(name, 80) : '';
|
|
175
|
+
if (!label) return null;
|
|
176
|
+
const derived = deriveRequest(deviceSecret);
|
|
177
|
+
if (!REQUEST_ID.test(derived.requestId)) return null;
|
|
178
|
+
return { deviceSecret, ...derived, name: label, createdAt: new Date(created).toISOString() };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function savePendingLogin(baseUrl, pending, deps) {
|
|
182
|
+
// The device secret can collect the key once approved: same rules as the key.
|
|
183
|
+
await assertPrivateConfigFile(deps, pendingPath(deps), 'a pending CueApril login');
|
|
184
|
+
const store = await readPendingStore(deps);
|
|
185
|
+
store.requests[baseUrl] = {
|
|
186
|
+
device_secret: pending.deviceSecret,
|
|
187
|
+
name: pending.name,
|
|
188
|
+
created_at: pending.createdAt,
|
|
189
|
+
};
|
|
190
|
+
await atomicWriteFile(deps, pendingPath(deps), `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export async function clearPendingLogin(baseUrl, deps) {
|
|
194
|
+
const file = pendingPath(deps);
|
|
195
|
+
const store = await readPendingStore(deps);
|
|
196
|
+
if (!(baseUrl in store.requests)) return;
|
|
197
|
+
delete store.requests[baseUrl];
|
|
198
|
+
if (Object.keys(store.requests).length === 0) await deps.fs.rm(file, { force: true }).catch(() => {});
|
|
199
|
+
else await atomicWriteFile(deps, file, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** False in CI, over SSH on macOS, and on Linux without a display. */
|
|
203
|
+
export function canOpenBrowser(deps) {
|
|
204
|
+
const env = deps.env;
|
|
205
|
+
if (env.CI && env.CI !== 'false' && env.CI !== '0') return false;
|
|
206
|
+
if (deps.platform === 'darwin') return !(env.SSH_CONNECTION || env.SSH_TTY);
|
|
207
|
+
if (deps.platform === 'win32') return true;
|
|
208
|
+
return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Opens a URL in the default browser without a shell. Failures are ignored. */
|
|
212
|
+
export function openBrowser(url, deps) {
|
|
213
|
+
const [command, args] =
|
|
214
|
+
deps.platform === 'darwin'
|
|
215
|
+
? ['open', [url]]
|
|
216
|
+
: deps.platform === 'win32'
|
|
217
|
+
? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
218
|
+
: ['xdg-open', [url]];
|
|
219
|
+
try {
|
|
220
|
+
const child = deps.spawn(command, args, { shell: false, stdio: 'ignore', detached: true, windowsHide: true });
|
|
221
|
+
child?.on?.('error', () => {});
|
|
222
|
+
child?.unref?.();
|
|
223
|
+
return true;
|
|
224
|
+
} catch {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function emitJson(deps, mode, event) {
|
|
230
|
+
if (mode.json) writeLine(deps.stdout, JSON.stringify(event));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function parseLoginArgs(argv) {
|
|
234
|
+
const { values } = parseArgs({
|
|
235
|
+
args: argv,
|
|
236
|
+
allowPositionals: false,
|
|
237
|
+
strict: true,
|
|
238
|
+
options: {
|
|
239
|
+
name: { type: 'string' },
|
|
240
|
+
'no-browser': { type: 'boolean' },
|
|
241
|
+
'print-key': { type: 'boolean' },
|
|
242
|
+
timeout: { type: 'string' },
|
|
243
|
+
'no-wait': { type: 'boolean' },
|
|
244
|
+
'key-stdin': { type: 'boolean' },
|
|
245
|
+
new: { type: 'boolean' },
|
|
246
|
+
json: { type: 'boolean' },
|
|
247
|
+
help: { type: 'boolean', short: 'h' },
|
|
248
|
+
},
|
|
249
|
+
});
|
|
250
|
+
return values;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function listText(list) {
|
|
254
|
+
return Array.isArray(list) && list.length ? list.join(', ') : 'none listed';
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Explicit key import is independent of the resumable browser approval flow. */
|
|
258
|
+
export async function importApiKey(deps = {}, { dryRun = false } = {}) {
|
|
259
|
+
const io = defaultDeps(deps);
|
|
260
|
+
if (['CUEAPRIL_API_KEY', 'TENHAW_TOKEN'].some((name) => typeof io.env[name] === 'string' && io.env[name].trim())) {
|
|
261
|
+
throw new CliError('--key-stdin cannot be combined with CUEAPRIL_API_KEY or TENHAW_TOKEN. Use the environment key, or unset it before importing.');
|
|
262
|
+
}
|
|
263
|
+
const baseUrl = resolveBaseUrl(io.env);
|
|
264
|
+
const key = await readApiKeyStdin(io);
|
|
265
|
+
try {
|
|
266
|
+
// Unlike check_setup, this read works when the key covers multiple projects.
|
|
267
|
+
await createHttpClient(io, { baseUrl }).callTool('cueapril_list_projects', {}, key, { timeoutMs: 30_000 });
|
|
268
|
+
} catch (error) {
|
|
269
|
+
throw new CliError(`${safeText(redact(error.message, [key]), 400)} Nothing was saved.`, { code: error.code ?? 'error' });
|
|
270
|
+
}
|
|
271
|
+
const previous = await readCredential(baseUrl, io).catch(() => null);
|
|
272
|
+
const changed = !dryRun && previous?.key !== key;
|
|
273
|
+
let credentialsPath = previous?.key === key ? pathFor(io).join(configDir(io), 'credentials.json') : null;
|
|
274
|
+
try {
|
|
275
|
+
if (changed) ({ path: credentialsPath } = await writeCredential(baseUrl, { key }, io));
|
|
276
|
+
} catch (error) {
|
|
277
|
+
throw new CliError(`Key verified, but local storage could not be confirmed: ${safeText(redact(error.message, [key]), 300)}`, { code: error.code ?? 'error' });
|
|
278
|
+
}
|
|
279
|
+
return { exitCode: EXIT.ok, status: 'imported', key, credentialsPath, saved: !dryRun, changed, baseUrl };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Runs the device approval flow. Returns
|
|
284
|
+
* { exitCode, status, key?, record?, credentialsPath?, verificationUrl?, code? };
|
|
285
|
+
* status is approved, pending (with --no-wait), timeout, declined or error.
|
|
286
|
+
* `options.embedded` (used by init) suppresses stdout; progress still goes to stderr.
|
|
287
|
+
*/
|
|
288
|
+
export async function runLogin(argv = [], deps = {}, options = {}) {
|
|
289
|
+
const io = defaultDeps(deps);
|
|
290
|
+
let flags;
|
|
291
|
+
try {
|
|
292
|
+
flags = parseLoginArgs(argv);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
writeLine(io.stderr, `${safeText(redact(error.message))}\n\n${LOGIN_USAGE}`);
|
|
295
|
+
return { exitCode: EXIT.error, status: 'error' };
|
|
296
|
+
}
|
|
297
|
+
if (flags.help) {
|
|
298
|
+
writeLine(options.embedded ? io.stderr : io.stdout, LOGIN_USAGE);
|
|
299
|
+
return { exitCode: EXIT.ok, status: 'help' };
|
|
300
|
+
}
|
|
301
|
+
const mode = {
|
|
302
|
+
json: !options.embedded && (Boolean(flags.json) || (!flags['print-key'] && !isTTY(io.stdout))),
|
|
303
|
+
printKey: Boolean(flags['print-key']),
|
|
304
|
+
embedded: Boolean(options.embedded),
|
|
305
|
+
};
|
|
306
|
+
let pending;
|
|
307
|
+
try {
|
|
308
|
+
if (flags['key-stdin']) {
|
|
309
|
+
if (['name', 'no-browser', 'print-key', 'timeout', 'no-wait', 'new'].some((name) => flags[name] !== undefined)) {
|
|
310
|
+
throw new CliError('--key-stdin cannot be combined with browser approval or --print-key options.');
|
|
311
|
+
}
|
|
312
|
+
const imported = await importApiKey(io);
|
|
313
|
+
writeLine(io.stderr, `Verified and saved key ${maskKey(imported.key)} to ${displayPath(io, imported.credentialsPath)}.`);
|
|
314
|
+
emitJson(io, mode, { event: 'login_imported', base_url: imported.baseUrl, credentials_path: displayPath(io, imported.credentialsPath), saved: true, exit_code: EXIT.ok });
|
|
315
|
+
return imported;
|
|
316
|
+
}
|
|
317
|
+
const baseUrl = resolveBaseUrl(io.env);
|
|
318
|
+
const timeoutMinutes = parseTimeoutMinutes(flags.timeout);
|
|
319
|
+
const requestedName = flags.name === undefined ? undefined : parseLabel(flags.name);
|
|
320
|
+
pending = flags.new ? null : await readPendingLogin(baseUrl, io);
|
|
321
|
+
if (pending && requestedName && pending.name !== requestedName) pending = null;
|
|
322
|
+
const resumed = Boolean(pending);
|
|
323
|
+
if (!pending) {
|
|
324
|
+
pending = {
|
|
325
|
+
...createDeviceRequest(io.randomBytes),
|
|
326
|
+
name: requestedName ?? defaultKeyLabel(io),
|
|
327
|
+
createdAt: new Date(io.now()).toISOString(),
|
|
328
|
+
};
|
|
329
|
+
await savePendingLogin(baseUrl, pending, io);
|
|
330
|
+
}
|
|
331
|
+
const url = verificationUrl(baseUrl, pending.requestId, pending.name);
|
|
332
|
+
const announce = {
|
|
333
|
+
url,
|
|
334
|
+
code: pending.code,
|
|
335
|
+
name: pending.name,
|
|
336
|
+
};
|
|
337
|
+
writeLine(io.stderr, resumed ? 'Resuming the CueApril approval request started earlier.' : 'Connect this agent to CueApril.');
|
|
338
|
+
writeLine(io.stderr, ` 1. Open: ${url}`);
|
|
339
|
+
writeLine(io.stderr, ` 2. Check the page shows the code ${pending.code}, then approve.`);
|
|
340
|
+
writeLine(io.stderr, ' (An organisation owner or admin must approve.)');
|
|
341
|
+
emitJson(io, mode, {
|
|
342
|
+
event: 'login_pending',
|
|
343
|
+
verification_url: url,
|
|
344
|
+
code: pending.code,
|
|
345
|
+
name: pending.name,
|
|
346
|
+
resumed,
|
|
347
|
+
wait_seconds: flags['no-wait'] ? 0 : Math.round(timeoutMinutes * 60),
|
|
348
|
+
poll_interval_seconds: POLL_INTERVAL_MS / 1000,
|
|
349
|
+
});
|
|
350
|
+
if (!resumed && !flags['no-browser'] && canOpenBrowser(io)) {
|
|
351
|
+
if (openBrowser(url, io)) writeLine(io.stderr, ' Opening your browser...');
|
|
352
|
+
}
|
|
353
|
+
if (flags['no-wait']) {
|
|
354
|
+
writeLine(io.stderr, 'After approval, run `cueapril login` (or `cueapril init`) again to finish; it reuses this link.');
|
|
355
|
+
return { exitCode: EXIT.ok, status: 'pending', verificationUrl: url, code: pending.code };
|
|
356
|
+
}
|
|
357
|
+
writeLine(io.stderr, `Waiting up to ${formatMinutes(timeoutMinutes)} for approval...`);
|
|
358
|
+
return await pollForApproval({ io, mode, baseUrl, pending, announce, timeoutMs: timeoutMinutes * 60_000 });
|
|
359
|
+
} catch (error) {
|
|
360
|
+
const message = safeText(redact(error.message), 500);
|
|
361
|
+
writeLine(io.stderr, `Error: ${message}`);
|
|
362
|
+
emitJson(io, mode, { event: 'login_failed', reason: error.code ?? 'error', message });
|
|
363
|
+
return { exitCode: error.exitCode ?? EXIT.error, status: 'error' };
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function formatMinutes(minutes) {
|
|
368
|
+
return minutes === 1 ? '1 minute' : `${minutes} minutes`;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function isFatal(error) {
|
|
372
|
+
if (!(error instanceof HttpError)) return true;
|
|
373
|
+
if (error.code === 'rate_limited' || error.code === 'timeout' || error.code === 'network_error') return false;
|
|
374
|
+
if (error.code === 'server_error') return false;
|
|
375
|
+
return true;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function pollForApproval({ io, mode, baseUrl, pending, announce, timeoutMs }) {
|
|
379
|
+
const client = createHttpClient(io, { baseUrl });
|
|
380
|
+
const start = io.now();
|
|
381
|
+
const deadline = start + timeoutMs;
|
|
382
|
+
let nextHeartbeat = start + HEARTBEAT_INTERVAL_MS;
|
|
383
|
+
let lastError = null;
|
|
384
|
+
for (;;) {
|
|
385
|
+
let delay = POLL_INTERVAL_MS;
|
|
386
|
+
let result = null;
|
|
387
|
+
try {
|
|
388
|
+
result = await client.request(CLAIM_PATH, {
|
|
389
|
+
method: 'POST',
|
|
390
|
+
body: { device_secret: pending.deviceSecret },
|
|
391
|
+
timeoutMs: 15_000,
|
|
392
|
+
maxBytes: 100_000,
|
|
393
|
+
});
|
|
394
|
+
lastError = null;
|
|
395
|
+
} catch (error) {
|
|
396
|
+
if (isFatal(error)) {
|
|
397
|
+
// The server consumes an approval when it answers a claim, so after a
|
|
398
|
+
// refusal (for example 410: no longer valid) the saved request is dead.
|
|
399
|
+
await clearPendingLogin(baseUrl, io).catch(() => {});
|
|
400
|
+
const notSupported = error.code === 'not_found';
|
|
401
|
+
const message = notSupported
|
|
402
|
+
? `This CueApril server (${baseUrl}) does not support agent login yet. Create a key in Settings and set CUEAPRIL_API_KEY instead.`
|
|
403
|
+
: `${error.message}${/login/i.test(error.message) ? '' : ' Run `cueapril login` again to start a new request.'}`;
|
|
404
|
+
writeLine(io.stderr, `Error: ${safeText(message, 500)}`);
|
|
405
|
+
emitJson(io, mode, { event: 'login_failed', reason: error.code ?? 'error', message: safeText(message, 500) });
|
|
406
|
+
return { exitCode: EXIT.error, status: 'error', verificationUrl: announce.url, code: announce.code };
|
|
407
|
+
}
|
|
408
|
+
lastError = error;
|
|
409
|
+
if (error.code === 'rate_limited' && error.retryAfterSeconds !== null) {
|
|
410
|
+
delay = Math.min(60_000, Math.max(POLL_INTERVAL_MS, error.retryAfterSeconds * 1000));
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (result && typeof result === 'object') {
|
|
414
|
+
const status = String(result.status ?? '').toLowerCase();
|
|
415
|
+
if (status === 'approved') return finishApproved({ io, mode, baseUrl, result, announce });
|
|
416
|
+
if (status === 'denied' || status === 'declined' || status === 'rejected') {
|
|
417
|
+
await clearPendingLogin(baseUrl, io);
|
|
418
|
+
writeLine(io.stderr, 'The request was declined in CueApril. Nothing was saved.');
|
|
419
|
+
emitJson(io, mode, { event: 'login_declined' });
|
|
420
|
+
return { exitCode: EXIT.error, status: 'declined' };
|
|
421
|
+
}
|
|
422
|
+
if (status === 'expired') {
|
|
423
|
+
await clearPendingLogin(baseUrl, io);
|
|
424
|
+
writeLine(io.stderr, 'The approval expired before this computer collected the key. Run `cueapril login` again.');
|
|
425
|
+
emitJson(io, mode, { event: 'login_expired' });
|
|
426
|
+
return { exitCode: EXIT.timeout, status: 'timeout' };
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const now = io.now();
|
|
430
|
+
if (now >= deadline) {
|
|
431
|
+
if (lastError) {
|
|
432
|
+
writeLine(io.stderr, `Error: ${safeText(lastError.message, 500)}`);
|
|
433
|
+
emitJson(io, mode, { event: 'login_failed', reason: lastError.code, message: safeText(lastError.message, 500) });
|
|
434
|
+
return { exitCode: EXIT.error, status: 'error', verificationUrl: announce.url, code: announce.code };
|
|
435
|
+
}
|
|
436
|
+
writeLine(io.stderr, 'Timed out waiting for approval. Run `cueapril login` again to keep waiting: the link and code stay the same.');
|
|
437
|
+
emitJson(io, mode, {
|
|
438
|
+
event: 'login_timeout',
|
|
439
|
+
verification_url: announce.url,
|
|
440
|
+
code: announce.code,
|
|
441
|
+
message: 'Approval not received in time. Run the same command again to keep waiting.',
|
|
442
|
+
});
|
|
443
|
+
return { exitCode: EXIT.timeout, status: 'timeout', verificationUrl: announce.url, code: announce.code };
|
|
444
|
+
}
|
|
445
|
+
if (now >= nextHeartbeat) {
|
|
446
|
+
const left = Math.max(1, Math.ceil((deadline - now) / 60_000));
|
|
447
|
+
const problem = lastError ? ` Last attempt failed: ${safeText(lastError.message, 200)}` : '';
|
|
448
|
+
writeLine(
|
|
449
|
+
io.stderr,
|
|
450
|
+
`Still waiting for approval (about ${formatMinutes(left)} left). Open ${announce.url} and check code ${announce.code}.${problem}`,
|
|
451
|
+
);
|
|
452
|
+
nextHeartbeat = now + HEARTBEAT_INTERVAL_MS;
|
|
453
|
+
}
|
|
454
|
+
await io.sleep(Math.max(0, Math.min(delay, deadline - now)));
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async function finishApproved({ io, mode, baseUrl, result, announce }) {
|
|
459
|
+
const key = result.key;
|
|
460
|
+
if (typeof key !== 'string' || !AGENT_KEY_PATTERN.test(key)) {
|
|
461
|
+
writeLine(io.stderr, 'Error: CueApril approved the request but returned a key in an unexpected format. Nothing was saved.');
|
|
462
|
+
emitJson(io, mode, { event: 'login_failed', reason: 'invalid_key' });
|
|
463
|
+
return { exitCode: EXIT.error, status: 'error' };
|
|
464
|
+
}
|
|
465
|
+
const record = sanitiseCredentialRecord(result);
|
|
466
|
+
const previous = await readCredential(baseUrl, io).catch(() => null);
|
|
467
|
+
let credentialsPath = null;
|
|
468
|
+
let saveError = null;
|
|
469
|
+
try {
|
|
470
|
+
({ path: credentialsPath } = await writeCredential(baseUrl, { ...record, key }, io));
|
|
471
|
+
} catch (error) {
|
|
472
|
+
saveError = error;
|
|
473
|
+
}
|
|
474
|
+
await clearPendingLogin(baseUrl, io).catch(() => {});
|
|
475
|
+
const masked = maskKey(key);
|
|
476
|
+
writeLine(
|
|
477
|
+
io.stderr,
|
|
478
|
+
`Approved: key "${record.name ?? announce.name}" (${masked})${record.organisation_name ? ` for ${record.organisation_name}` : ''}.`,
|
|
479
|
+
);
|
|
480
|
+
const spendCap =
|
|
481
|
+
Number.isSafeInteger(result.spend_cap_pence) && result.spend_cap_pence >= 0 ? result.spend_cap_pence : null;
|
|
482
|
+
writeLine(io.stderr, ` Projects: ${listText(record.project_ids)}`);
|
|
483
|
+
writeLine(io.stderr, ` Access: ${listText(record.scopes)}`);
|
|
484
|
+
writeLine(io.stderr, ` Expires: ${record.expires_at ?? 'not stated'}`);
|
|
485
|
+
writeLine(io.stderr, ` Spend cap: ${spendCap === null ? 'none set on the key' : `${spendCap}p per 30 days`}`);
|
|
486
|
+
if (credentialsPath) writeLine(io.stderr, ` Saved to: ${displayPath(io, credentialsPath)}`);
|
|
487
|
+
// init only logs in when there is no stored key or it was rejected, so the
|
|
488
|
+
// note applies to an explicit `cueapril login` only.
|
|
489
|
+
if (credentialsPath && previous && previous.key !== key && !mode.embedded) {
|
|
490
|
+
writeLine(
|
|
491
|
+
io.stderr,
|
|
492
|
+
` Replaced the previously stored key ${maskKey(previous.key)}; it stays valid until it expires or is revoked in Settings.`,
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
if (saveError) {
|
|
496
|
+
writeLine(io.stderr, `Error: the key could not be saved: ${safeText(saveError.message, 300)}`);
|
|
497
|
+
if (!mode.printKey) {
|
|
498
|
+
writeLine(io.stderr, 'Revoke it in CueApril Settings, fix the problem and run `cueapril login` again.');
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const event = {
|
|
502
|
+
event: 'login_approved',
|
|
503
|
+
base_url: baseUrl,
|
|
504
|
+
key_id: record.id ?? null,
|
|
505
|
+
key_prefix: record.key_prefix ?? null,
|
|
506
|
+
name: record.name ?? announce.name,
|
|
507
|
+
organisation_name: record.organisation_name ?? null,
|
|
508
|
+
project_ids: record.project_ids ?? [],
|
|
509
|
+
scopes: record.scopes ?? [],
|
|
510
|
+
expires_at: record.expires_at ?? null,
|
|
511
|
+
spend_cap_pence: spendCap,
|
|
512
|
+
credentials_path: credentialsPath,
|
|
513
|
+
saved: Boolean(credentialsPath),
|
|
514
|
+
};
|
|
515
|
+
if (mode.printKey) event.key = key;
|
|
516
|
+
emitJson(io, mode, event);
|
|
517
|
+
if (mode.printKey && !mode.json) writeLine(io.stdout, key);
|
|
518
|
+
return {
|
|
519
|
+
exitCode: saveError ? EXIT.error : EXIT.ok,
|
|
520
|
+
status: 'approved',
|
|
521
|
+
key,
|
|
522
|
+
record,
|
|
523
|
+
credentialsPath,
|
|
524
|
+
saved: Boolean(credentialsPath),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Revokes the stored key on the server (DELETE with the key as bearer) and
|
|
530
|
+
* deletes the local copy. With --local, only the local copy is deleted.
|
|
531
|
+
*/
|
|
532
|
+
export async function runLogout(argv = [], deps = {}) {
|
|
533
|
+
const io = defaultDeps(deps);
|
|
534
|
+
let flags;
|
|
535
|
+
try {
|
|
536
|
+
({ values: flags } = parseArgs({
|
|
537
|
+
args: argv,
|
|
538
|
+
allowPositionals: false,
|
|
539
|
+
strict: true,
|
|
540
|
+
options: { local: { type: 'boolean' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } },
|
|
541
|
+
}));
|
|
542
|
+
} catch (error) {
|
|
543
|
+
writeLine(io.stderr, `${safeText(error.message)}\n\n${LOGOUT_USAGE}`);
|
|
544
|
+
return { exitCode: EXIT.error };
|
|
545
|
+
}
|
|
546
|
+
if (flags.help) {
|
|
547
|
+
writeLine(io.stdout, LOGOUT_USAGE);
|
|
548
|
+
return { exitCode: EXIT.ok };
|
|
549
|
+
}
|
|
550
|
+
const report = (exitCode, summary) => {
|
|
551
|
+
if (flags.json) writeLine(io.stdout, JSON.stringify({ ok: exitCode === EXIT.ok, exit_code: exitCode, ...summary }));
|
|
552
|
+
return { exitCode, ...summary };
|
|
553
|
+
};
|
|
554
|
+
try {
|
|
555
|
+
const baseUrl = resolveBaseUrl(io.env);
|
|
556
|
+
await clearPendingLogin(baseUrl, io).catch(() => {});
|
|
557
|
+
const stored = await readCredential(baseUrl, io);
|
|
558
|
+
const envName = ['CUEAPRIL_API_KEY', 'TENHAW_TOKEN'].find(
|
|
559
|
+
(name) => typeof io.env[name] === 'string' && io.env[name].trim(),
|
|
560
|
+
);
|
|
561
|
+
const envNote = envName ? `${envName} is still set in your environment; unset it to stop using that key.` : null;
|
|
562
|
+
if (!stored) {
|
|
563
|
+
writeLine(io.stderr, `No key is stored for ${baseUrl}.`);
|
|
564
|
+
if (envNote) writeLine(io.stderr, envNote);
|
|
565
|
+
return report(EXIT.ok, { base_url: baseUrl, revoked: false, deleted: false, note: envNote });
|
|
566
|
+
}
|
|
567
|
+
let revoked = false;
|
|
568
|
+
if (!flags.local) {
|
|
569
|
+
try {
|
|
570
|
+
await createHttpClient(io, { baseUrl }).request(SELF_REVOKE_PATH, {
|
|
571
|
+
method: 'DELETE',
|
|
572
|
+
key: stored.key,
|
|
573
|
+
timeoutMs: 15_000,
|
|
574
|
+
});
|
|
575
|
+
revoked = true;
|
|
576
|
+
} catch (error) {
|
|
577
|
+
if (error instanceof HttpError && error.status === 401) {
|
|
578
|
+
revoked = true; // The server no longer accepts it: already revoked or expired.
|
|
579
|
+
} else {
|
|
580
|
+
writeLine(io.stderr, `Error: could not revoke the key on the server: ${safeText(error.message, 300)}`);
|
|
581
|
+
writeLine(io.stderr, 'The local copy was kept so you can retry. Use --local to delete only the local copy.');
|
|
582
|
+
return report(EXIT.error, { base_url: baseUrl, revoked: false, deleted: false });
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const { path } = await deleteCredential(baseUrl, io);
|
|
587
|
+
writeLine(
|
|
588
|
+
io.stderr,
|
|
589
|
+
`${revoked ? 'Revoked and removed' : 'Removed'} key ${maskKey(stored.key)} from ${displayPath(io, path)}.`,
|
|
590
|
+
);
|
|
591
|
+
writeLine(
|
|
592
|
+
io.stderr,
|
|
593
|
+
'Agent MCP settings written by `cueapril init` still hold the old key; run `cueapril init` after logging in again.',
|
|
594
|
+
);
|
|
595
|
+
if (envNote) writeLine(io.stderr, envNote);
|
|
596
|
+
return report(EXIT.ok, { base_url: baseUrl, revoked, deleted: true, note: envNote });
|
|
597
|
+
} catch (error) {
|
|
598
|
+
writeLine(io.stderr, `Error: ${safeText(error.message, 500)}`);
|
|
599
|
+
return report(error.exitCode ?? EXIT.error, { error: safeText(error.message, 500) });
|
|
600
|
+
}
|
|
601
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cueapril",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "CueApril CLI: connect your coding agent to CueApril in one command, then test pull requests and read verdicts, findings and suggested fixes from the terminal.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cueapril",
|
|
7
|
+
"qa",
|
|
8
|
+
"testing",
|
|
9
|
+
"pull-request",
|
|
10
|
+
"code-review",
|
|
11
|
+
"mcp",
|
|
12
|
+
"ai-agents",
|
|
13
|
+
"claude-code",
|
|
14
|
+
"codex",
|
|
15
|
+
"gemini-cli",
|
|
16
|
+
"cursor",
|
|
17
|
+
"cli"
|
|
18
|
+
],
|
|
19
|
+
"homepage": "https://app.cueapril.com/agents",
|
|
20
|
+
"license": "UNLICENSED",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"bin": {
|
|
23
|
+
"cueapril": "cli.mjs"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"agents.mjs",
|
|
27
|
+
"cli.mjs",
|
|
28
|
+
"client.mjs",
|
|
29
|
+
"commands.mjs",
|
|
30
|
+
"doctor.mjs",
|
|
31
|
+
"http.mjs",
|
|
32
|
+
"init.mjs",
|
|
33
|
+
"io.mjs",
|
|
34
|
+
"key-store.mjs",
|
|
35
|
+
"login.mjs",
|
|
36
|
+
"skill/"
|
|
37
|
+
],
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=20"
|
|
40
|
+
}
|
|
41
|
+
}
|