@blinkhost/cli 2.3.0 → 2.5.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +246 -0
  2. package/README.md +251 -3
  3. package/dist/api.d.ts +1 -0
  4. package/dist/api.js +129 -2
  5. package/dist/assistant.d.ts +7 -0
  6. package/dist/assistant.js +460 -0
  7. package/dist/auth.d.ts +1 -0
  8. package/dist/auth.js +21 -24
  9. package/dist/cli.js +39 -13
  10. package/dist/compatibility.d.ts +1 -0
  11. package/dist/compatibility.js +43 -0
  12. package/dist/config.d.ts +2 -0
  13. package/dist/config.js +9 -1
  14. package/dist/credential-process.d.ts +19 -0
  15. package/dist/credential-process.js +75 -0
  16. package/dist/credentials.d.ts +4 -0
  17. package/dist/credentials.js +45 -46
  18. package/dist/device-flow.d.ts +24 -0
  19. package/dist/device-flow.js +76 -0
  20. package/dist/guidance.d.ts +1 -1
  21. package/dist/guidance.js +68 -5
  22. package/dist/macos-keychain-input.d.ts +6 -0
  23. package/dist/macos-keychain-input.js +22 -0
  24. package/dist/module-build.d.ts +7 -0
  25. package/dist/module-build.js +37 -0
  26. package/dist/peer-review.d.ts +8 -0
  27. package/dist/peer-review.js +55 -0
  28. package/dist/project-export.d.ts +1 -0
  29. package/dist/project-export.js +79 -0
  30. package/dist/research.d.ts +1 -0
  31. package/dist/research.js +42 -0
  32. package/dist/starter.d.ts +11 -0
  33. package/dist/starter.js +45 -0
  34. package/dist/templates.js +10 -8
  35. package/dist/terminal.d.ts +2 -0
  36. package/dist/terminal.js +12 -0
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/dist/windows-vault-command.d.ts +12 -0
  40. package/dist/windows-vault-command.js +42 -0
  41. package/dist/workflows.d.ts +17 -1
  42. package/dist/workflows.js +76 -4
  43. package/package.json +2 -2
package/dist/auth.js CHANGED
@@ -2,11 +2,11 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { hostname } from 'node:os';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { activeProfile, validateApiOrigin, validateProfileName, writeConfig } from './config.js';
5
- import { deleteRefreshCredential, setRefreshCredential } from './credentials.js';
5
+ import { credentialStoreStatus, deleteRefreshCredential, setRefreshCredential } from './credentials.js';
6
6
  import { ApiClient, publicRequest } from './api.js';
7
7
  import { CliError, EXIT } from './errors.js';
8
8
  import { VERSION } from './version.js';
9
- const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
9
+ import { pollDeviceAuthorization, validateDeviceAuthorization, validateDeviceTokens } from './device-flow.js';
10
10
  function openBrowser(url) {
11
11
  const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd.exe' : 'xdg-open';
12
12
  const args = process.platform === 'win32' ? ['/d', '/s', '/c', 'start', '', url] : [url];
@@ -18,6 +18,13 @@ function errorCode(data) {
18
18
  return data && typeof data === 'object' && typeof data.error === 'string' ? data.error : '';
19
19
  }
20
20
  export async function login(options) {
21
+ if (options.scopes && (options.scopes.length > 30 || options.scopes.some(scope => !/^[a-z]+:(?:read|write|execute|approve)$/.test(scope)))) {
22
+ throw new CliError('Use repeated --scope values such as ai:read or ai:execute.', EXIT.usage, 'invalid_scope');
23
+ }
24
+ const credentialStore = await credentialStoreStatus();
25
+ if (!credentialStore.available) {
26
+ throw new CliError(`Secure credential storage is unavailable. ${credentialStore.remediation || 'Set up your operating-system credential service before signing in.'}`, EXIT.auth, 'credential_store_unavailable');
27
+ }
21
28
  const selected = await activeProfile(options.profile);
22
29
  const profileName = validateProfileName(options.profile || selected.name);
23
30
  const apiOrigin = validateApiOrigin(options.apiOrigin || selected.profile.apiOrigin);
@@ -25,35 +32,25 @@ export async function login(options) {
25
32
  const challenge = createHash('sha256').update(verifier).digest('base64url');
26
33
  const started = await publicRequest(apiOrigin, '/api/cli/v2/device/start/', {
27
34
  method: 'POST',
28
- body: JSON.stringify({ code_challenge: challenge, client_name: 'BlinkHost CLI', client_version: VERSION, device_name: hostname().slice(0, 120) }),
35
+ body: JSON.stringify({ code_challenge: challenge, client_name: 'BlinkHost CLI', client_version: VERSION, device_name: hostname().slice(0, 120),
36
+ ...(options.scopes ? { scopes: [...new Set(['account:read', ...options.scopes])] } : {}) }),
29
37
  });
30
38
  if (!started.response.ok)
31
39
  throw new CliError('BlinkHost could not start CLI authorization.', EXIT.auth, errorCode(started.data) || 'authorization_start_failed');
32
- const device = started.data;
40
+ const device = validateDeviceAuthorization(started.data);
33
41
  options.progress?.(`Open ${device.verification_uri_complete}`);
34
42
  options.progress?.(`Confirm code ${device.user_code}`);
35
43
  if (options.openBrowser !== false)
36
44
  openBrowser(device.verification_uri_complete);
37
- const deadline = Date.now() + device.expires_in * 1000;
38
- while (Date.now() < deadline) {
39
- await sleep(Math.max(device.interval, 5) * 1000);
40
- const polled = await publicRequest(apiOrigin, '/api/cli/v2/device/poll/', { method: 'POST', body: JSON.stringify({ device_code: device.device_code, code_verifier: verifier }) });
41
- const code = errorCode(polled.data);
42
- if (code === 'authorization_pending' || code === 'slow_down')
43
- continue;
44
- if (!polled.response.ok)
45
- throw new CliError(code === 'access_denied' ? 'CLI authorization was denied.' : 'CLI authorization could not be completed.', EXIT.auth, code || 'authorization_failed');
46
- const tokens = polled.data;
47
- await setRefreshCredential(profileName, tokens.refresh_token);
48
- selected.config.profiles[profileName] = { apiOrigin };
49
- selected.config.activeProfile = profileName;
50
- await writeConfig(selected.config);
51
- const client = await ApiClient.create(profileName);
52
- const capabilities = await client.request('/api/cli/v2/capabilities/');
53
- await client.rememberIdentity(capabilities.actor || {});
54
- return { profile: profileName, api_origin: apiOrigin, account: capabilities.actor, permissions: capabilities.features };
55
- }
56
- throw new CliError('CLI authorization expired before it was approved.', EXIT.auth, 'authorization_expired');
45
+ const tokens = validateDeviceTokens(await pollDeviceAuthorization(apiOrigin, device, verifier));
46
+ await setRefreshCredential(profileName, tokens.refresh_token);
47
+ selected.config.profiles[profileName] = { apiOrigin };
48
+ selected.config.activeProfile = profileName;
49
+ await writeConfig(selected.config);
50
+ const client = await ApiClient.create(profileName);
51
+ const capabilities = await client.request('/api/cli/v2/capabilities/');
52
+ await client.rememberIdentity(capabilities.actor || {});
53
+ return { profile: profileName, api_origin: apiOrigin, account: capabilities.actor, permissions: capabilities.features };
57
54
  }
58
55
  export async function logout(profile) {
59
56
  const selected = await activeProfile(profile);
package/dist/cli.js CHANGED
@@ -10,25 +10,25 @@ import { readProjectManifest, resolveLocalPath, validateProject, writeManifest,
10
10
  import { createScaffold } from './templates.js';
11
11
  import { ApiClient } from './api.js';
12
12
  import { login, logout } from './auth.js';
13
+ import { runAssistant } from './assistant.js';
14
+ import { exportProject } from './project-export.js';
13
15
  import { activeProfile, readConfig, validateProfileName, writeConfig } from './config.js';
14
16
  import { openPreview, projectStatus, rawApi, readProjectLink, runFunctions, runRemote, runSecrets, syncProject, unlinkProject, uploadAsset, waitForRemote, writeProjectLink } from './remote.js';
15
- import { checkForUpdate, ciCheck, completion, observability, runDev, runPlugins, supportBundle, testProject } from './workflows.js';
17
+ import { checkForUpdate, ciCheck, completion, maybeUpdateNotice, observability, releaseNotes, runDev, runPlugins, supportBundle, testProject } from './workflows.js';
16
18
  import { documentationIndex, documentationTopic, quickstart, renderTopHelp, renderTopic, searchDocumentation, TOP_LEVEL_COMMANDS } from './guidance.js';
17
19
  import { VERSION, supportedNodeVersion } from './version.js';
20
+ import { terminalJson, terminalText } from './terminal.js';
18
21
  let quietOutput = false;
19
22
  let verboseOutput = false;
20
- function terminalText(value) {
21
- return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, '');
22
- }
23
23
  function emit(output, json) {
24
24
  if (json)
25
- process.stdout.write(`${JSON.stringify(output)}\n`);
25
+ process.stdout.write(`${terminalJson(JSON.stringify(output))}\n`);
26
26
  else {
27
27
  if (quietOutput)
28
28
  return;
29
29
  process.stdout.write(`${terminalText(output.message)}\n`);
30
30
  if (output.data !== undefined && output.data !== null) {
31
- process.stdout.write(`${terminalText(JSON.stringify(output.data, null, 2))}\n`);
31
+ process.stdout.write(`${terminalJson(JSON.stringify(output.data, null, 2))}\n`);
32
32
  }
33
33
  for (const warning of output.warnings ?? [])
34
34
  process.stderr.write(`Warning: ${terminalText(warning)}\n`);
@@ -182,7 +182,7 @@ async function commandManifest(args, json) {
182
182
  if (json)
183
183
  emit({ ok: true, command: 'manifest', message: 'Manifest parsed.', data: manifest }, true);
184
184
  else
185
- process.stdout.write(`${JSON.stringify(manifest, null, 2)}\n`);
185
+ process.stdout.write(`${terminalJson(JSON.stringify(manifest, null, 2))}\n`);
186
186
  }
187
187
  async function commandDoctor(args, json) {
188
188
  const path = args.shift();
@@ -315,15 +315,20 @@ export async function main(argv = process.argv.slice(2)) {
315
315
  const data = await testProject(args, json);
316
316
  emit({ ok: true, command, message: 'Project checks passed.', data }, json);
317
317
  }
318
+ else if (command === 'ai') {
319
+ const result = await runAssistant(args, profile);
320
+ emit({ ok: true, command: 'ai', ...result }, json);
321
+ }
318
322
  else if (command === 'auth') {
319
323
  const action = args.shift() || 'status';
320
324
  if (action === 'login') {
321
325
  const apiOrigin = takeOption(args, '--api-origin');
322
326
  const noBrowser = takeFlag(args, '--no-browser');
327
+ const scopes = takeRepeatedOption(args, '--scope');
323
328
  assertNoUnknown(args);
324
329
  if (nonInteractive)
325
330
  throw new CliError('Interactive account authorization is disabled. Use an approved workload identity in automation.', EXIT.auth, 'interaction_required');
326
- const data = await login({ ...(profile ? { profile } : {}), ...(apiOrigin ? { apiOrigin } : {}), openBrowser: !noBrowser, ...(!json && !quietOutput ? { progress: (line) => { process.stderr.write(`${terminalText(line)}\n`); } } : {}) });
331
+ const data = await login({ ...(profile ? { profile } : {}), ...(apiOrigin ? { apiOrigin } : {}), ...(scopes.length ? { scopes } : {}), openBrowser: !noBrowser, ...(!json && !quietOutput ? { progress: (line) => { process.stderr.write(`${terminalText(line)}\n`); } } : {}) });
327
332
  emit({ ok: true, command: 'auth login', message: 'This device is connected to BlinkHost.', data }, json);
328
333
  }
329
334
  else if (action === 'logout') {
@@ -405,6 +410,11 @@ export async function main(argv = process.argv.slice(2)) {
405
410
  const data = await projectStatus(profile);
406
411
  emit({ ok: true, command: 'projects status', message: 'Project and source connection status loaded.', data }, json);
407
412
  }
413
+ else if (command === 'projects' && args[0] === 'export') {
414
+ args.shift();
415
+ const data = await exportProject(args, profile);
416
+ emit({ ok: true, command: 'projects export', message: 'Project source archive saved. This is not a database backup or a portable running deployment.', data }, json);
417
+ }
408
418
  else if (command === 'projects' && (args[0] === 'pull' || args[0] === 'push')) {
409
419
  const action = args.shift();
410
420
  const data = await syncProject(action, args, profile);
@@ -457,10 +467,21 @@ export async function main(argv = process.argv.slice(2)) {
457
467
  else
458
468
  process.stdout.write(output);
459
469
  }
460
- else if (command === 'update' && args.shift() === 'check') {
461
- assertNoUnknown(args);
462
- const data = await checkForUpdate();
463
- emit({ ok: true, command: 'update check', message: 'Release check completed.', data }, json);
470
+ else if (command === 'update') {
471
+ const action = args.shift() || 'check';
472
+ if (action === 'check') {
473
+ assertNoUnknown(args);
474
+ const data = await checkForUpdate(profile);
475
+ emit({ ok: true, command: 'update check', message: 'Release check completed. Updates are never installed automatically.', data }, json);
476
+ }
477
+ else if (action === 'notes') {
478
+ const version = args.shift();
479
+ assertNoUnknown(args);
480
+ const data = await releaseNotes(version, profile);
481
+ emit({ ok: true, command: 'update notes', message: version ? `Release notes for ${version}.` : 'Published CLI release notes.', data }, json);
482
+ }
483
+ else
484
+ throw new CliError(`Unknown update action: ${action}.`, EXIT.usage, 'unknown_action');
464
485
  }
465
486
  else if (command === 'ci' && args.shift() === 'check') {
466
487
  assertNoUnknown(args);
@@ -479,12 +500,17 @@ export async function main(argv = process.argv.slice(2)) {
479
500
  const suggestion = commandSuggestion(command);
480
501
  throw new CliError(`Unknown command: ${command}.${suggestion ? ` Did you mean \`${suggestion}\`?` : ' Run `blinkhost docs` to list commands.'}`, EXIT.usage, 'unknown_command');
481
502
  }
503
+ if (!json && !quietOutput && !nonInteractive && command !== 'update') {
504
+ const notice = await maybeUpdateNotice(profile);
505
+ if (notice)
506
+ process.stderr.write(`\n${terminalText(notice)}\n`);
507
+ }
482
508
  return EXIT.success;
483
509
  }
484
510
  catch (error) {
485
511
  const failure = error instanceof CliError ? error : new CliError(error instanceof Error ? error.message : String(error), EXIT.internal, 'internal_error');
486
512
  if (json)
487
- process.stdout.write(`${JSON.stringify({ ok: false, command: command ?? '', error: { code: failure.code, message: failure.message, details: failure.details } })}\n`);
513
+ process.stdout.write(`${terminalJson(JSON.stringify({ ok: false, command: command ?? '', error: { code: failure.code, message: failure.message, details: failure.details } }))}\n`);
488
514
  else {
489
515
  process.stderr.write(`Error: ${terminalText(failure.message)}\n`);
490
516
  for (const detail of failure.details)
@@ -0,0 +1 @@
1
+ export declare function validateCompatibility(value: unknown, projectId: string): void;
@@ -0,0 +1,43 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ const codes = new Set(['node_server', 'native_dependency', 'persistent_connections',
3
+ 'framework_server_features', 'python_server', 'python_native_dependency', 'manifest_not_inspected', 'manifest_incomplete']);
4
+ const pythonSections = new Set(['project.dependencies', 'project.optional-dependencies', 'build-system.requires']);
5
+ const sections = new Set(['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies', 'requirements', ...pythonSections]);
6
+ const pythonQualifiers = (version, path, qualifiers) => {
7
+ if (version !== 2 && version !== 3)
8
+ return false;
9
+ if (qualifiers.length === 1 && qualifiers[0] === 'requirements') {
10
+ return version === 2 || path.split('/').at(-1) === 'requirements.txt';
11
+ }
12
+ return version === 3 && path.split('/').at(-1) === 'pyproject.toml'
13
+ && qualifiers.length > 0 && qualifiers.every(section => typeof section === 'string' && pythonSections.has(section));
14
+ };
15
+ const count = (value, max) => Number.isSafeInteger(value) && Number(value) >= 0 && Number(value) <= max;
16
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
17
+ // Bind remote evidence to this project and known declaration-only semantics.
18
+ // This validates output, never resolves packages or runs local code.
19
+ export function validateCompatibility(value, projectId) {
20
+ if (!object(value) || value.project_id !== projectId || value.schema_version !== 1 || (value.rules_version !== 1 && value.rules_version !== 2 && value.rules_version !== 3)
21
+ || typeof value.revision !== 'string' || !/^[a-f0-9]{64}$/.test(value.revision)
22
+ || value.verification !== 'declaration_review_only' || value.backend_runtime !== 'wasm'
23
+ || !count(value.findings_omitted, 8000) || !Array.isArray(value.findings) || value.findings.length > 128
24
+ || value.findings.some(f => !object(f) || typeof f.code !== 'string' || !codes.has(f.code)
25
+ || typeof f.path !== 'string' || !f.path || Buffer.byteLength(f.path) > 8447 || /[\x00-\x1f]/.test(f.path)
26
+ || (f.package !== null && (typeof f.package !== 'string' || f.package.length > 202))
27
+ || !Array.isArray(f.sections) || f.sections.length > 4 || new Set(f.sections).size !== f.sections.length
28
+ || f.sections.some(s => typeof s !== 'string' || !sections.has(s))
29
+ || (f.code.startsWith('python_')
30
+ ? !pythonQualifiers(value.rules_version, f.path, f.sections)
31
+ : f.sections.some(section => section === 'requirements' || pythonSections.has(section)))
32
+ || (f.code.startsWith('manifest_') ? f.package !== null || f.sections.length !== 0 : !f.package || !f.sections.length))
33
+ || !object(value.coverage) || !count(value.coverage.projected_files, 2000) || !count(value.coverage.package_manifests, 2000)
34
+ || Number(value.coverage.package_manifests) > Number(value.coverage.projected_files)
35
+ || !count(value.coverage.inspected_package_manifests, 32)
36
+ || Number(value.coverage.inspected_package_manifests) > Number(value.coverage.package_manifests)
37
+ || typeof value.coverage.projection_limit_reached !== 'boolean'
38
+ || !Array.isArray(value.limitations) || value.limitations.length < 1 || value.limitations.length > 10
39
+ || value.limitations.some(note => typeof note !== 'string' || note.length > 2048)) {
40
+ throw new CliError('The project review could not be verified. No compatibility or runtime support can be inferred. Review blinkhost docs ai.', EXIT.remote, 'compatibility_response_invalid');
41
+ }
42
+ }
43
+ //# sourceMappingURL=compatibility.js.map
package/dist/config.d.ts CHANGED
@@ -15,6 +15,8 @@ export interface CliConfig {
15
15
  plugins?: Record<string, PluginRecord>;
16
16
  updateCheckedAt?: string;
17
17
  latestVersion?: string;
18
+ latestReleaseUrl?: string;
19
+ updateNotifications?: boolean;
18
20
  }
19
21
  export declare function configPath(): string;
20
22
  export declare function validateProfileName(value: string): string;
package/dist/config.js CHANGED
@@ -41,7 +41,15 @@ export async function readConfig() {
41
41
  continue;
42
42
  profiles[name] = { ...profile, apiOrigin: validateApiOrigin(profile.apiOrigin) };
43
43
  }
44
- return { activeProfile: validateProfileName(parsed.activeProfile || 'default'), profiles, plugins: parsed.plugins || {} };
44
+ return {
45
+ activeProfile: validateProfileName(parsed.activeProfile || 'default'),
46
+ profiles,
47
+ plugins: parsed.plugins || {},
48
+ ...(typeof parsed.updateCheckedAt === 'string' ? { updateCheckedAt: parsed.updateCheckedAt } : {}),
49
+ ...(typeof parsed.latestVersion === 'string' ? { latestVersion: parsed.latestVersion } : {}),
50
+ ...(typeof parsed.latestReleaseUrl === 'string' ? { latestReleaseUrl: parsed.latestReleaseUrl } : {}),
51
+ ...(typeof parsed.updateNotifications === 'boolean' ? { updateNotifications: parsed.updateNotifications } : {}),
52
+ };
45
53
  }
46
54
  catch (error) {
47
55
  if (error.code === 'ENOENT')
@@ -0,0 +1,19 @@
1
+ type Options = {
2
+ input?: string;
3
+ timeoutMs?: number;
4
+ missing?: {
5
+ code: number;
6
+ requireEmptyStderr: boolean;
7
+ };
8
+ };
9
+ export type CredentialProbe = {
10
+ available: true;
11
+ } | {
12
+ available: false;
13
+ failureCode: 'credential_store_timeout' | 'credential_store_unavailable' | 'credential_store_response_invalid' | 'credential_store_failed';
14
+ };
15
+ /** Read-only availability checks retain a safe category, never native output. */
16
+ export declare function credentialProbe(command: string, args: string[], timeoutMs?: number): Promise<CredentialProbe>;
17
+ /** OS credential helpers only; never retry a possibly completed credential write. */
18
+ export declare function credentialCommand(command: string, args: string[], options?: Options): Promise<string>;
19
+ export {};
@@ -0,0 +1,75 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { CliError, EXIT } from './errors.js';
3
+ const MAX_OUTPUT_BYTES = 16 * 1024;
4
+ /** Read-only availability checks retain a safe category, never native output. */
5
+ export async function credentialProbe(command, args, timeoutMs = 5000) {
6
+ try {
7
+ await credentialCommand(command, args, { timeoutMs });
8
+ return { available: true };
9
+ }
10
+ catch (error) {
11
+ const code = error instanceof CliError ? error.code : undefined;
12
+ const failureCode = code === 'credential_store_timeout' || code === 'credential_store_unavailable'
13
+ || code === 'credential_store_response_invalid' ? code : 'credential_store_failed';
14
+ return { available: false, failureCode };
15
+ }
16
+ }
17
+ /** OS credential helpers only; never retry a possibly completed credential write. */
18
+ export async function credentialCommand(command, args, options = {}) {
19
+ const timeoutMs = options.timeoutMs ?? 30_000;
20
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30_000) {
21
+ throw new CliError('Invalid credential-service timeout.', EXIT.internal, 'credential_store_configuration_invalid');
22
+ }
23
+ return new Promise((resolve, reject) => {
24
+ const child = spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
25
+ const chunks = [];
26
+ let bytes = 0;
27
+ let stderrPresent = false;
28
+ let finished = false;
29
+ const finish = (error, value = '') => {
30
+ if (finished)
31
+ return;
32
+ finished = true;
33
+ clearTimeout(timer);
34
+ if (error) {
35
+ child.kill('SIGKILL');
36
+ child.stdin.destroy();
37
+ child.stdout.destroy();
38
+ child.stderr.destroy();
39
+ reject(error);
40
+ }
41
+ else
42
+ resolve(value);
43
+ };
44
+ const failed = () => new CliError('The operating-system credential service could not complete the request. Unlock or restart your keyring and try again. If this happened after browser approval, review CLI sessions in BlinkHost settings before starting another sign-in.', EXIT.auth, 'credential_store_failed');
45
+ const timer = setTimeout(() => finish(new CliError('The operating-system credential service did not respond in time. Unlock or restart your keyring. If browser approval already succeeded, review CLI sessions in BlinkHost settings before starting another sign-in.', EXIT.auth, 'credential_store_timeout')), timeoutMs);
46
+ const collect = (chunk, stderr) => {
47
+ if (finished)
48
+ return;
49
+ bytes += chunk.length;
50
+ if (bytes > MAX_OUTPUT_BYTES) {
51
+ finish(new CliError('The operating-system credential service returned an unexpected response. No diagnostic output was displayed.', EXIT.auth, 'credential_store_response_invalid'));
52
+ return;
53
+ }
54
+ if (stderr)
55
+ stderrPresent ||= chunk.length > 0;
56
+ else
57
+ chunks.push(chunk);
58
+ };
59
+ child.stdout.on('data', (chunk) => collect(chunk, false));
60
+ child.stderr.on('data', (chunk) => collect(chunk, true));
61
+ child.stdin.on('error', () => finish(failed()));
62
+ child.once('error', () => finish(new CliError('No supported operating-system credential service is available.', EXIT.auth, 'credential_store_unavailable')));
63
+ child.once('close', code => {
64
+ if (code === 0)
65
+ finish(undefined, Buffer.concat(chunks).toString('utf8').trim());
66
+ else if (options.missing && code === options.missing.code
67
+ && (!options.missing.requireEmptyStderr || !stderrPresent))
68
+ finish();
69
+ else
70
+ finish(failed());
71
+ });
72
+ child.stdin.end(options.input);
73
+ });
74
+ }
75
+ //# sourceMappingURL=credential-process.js.map
@@ -1,7 +1,11 @@
1
+ import { type CredentialProbe } from './credential-process.js';
1
2
  export interface CredentialStoreStatus {
2
3
  available: boolean;
3
4
  provider: 'macos-keychain' | 'windows-password-vault' | 'linux-secret-service';
4
5
  remediation: string | null;
6
+ failureCode?: Extract<CredentialProbe, {
7
+ available: false;
8
+ }>['failureCode'];
5
9
  }
6
10
  /** Checks only whether the platform credential service can be invoked. */
7
11
  export declare function credentialStoreStatus(): Promise<CredentialStoreStatus>;
@@ -1,73 +1,70 @@
1
- import { spawn } from 'node:child_process';
2
1
  import { CliError, EXIT } from './errors.js';
2
+ import { credentialCommand, credentialProbe } from './credential-process.js';
3
+ import { macosKeychainWrite } from './macos-keychain-input.js';
4
+ import { windowsVaultCommand, windowsVaultProbe } from './windows-vault-command.js';
3
5
  const SERVICE = 'blinkhost-cli';
4
- async function executableAvailable(command, args) {
5
- return new Promise((resolve) => {
6
- const child = spawn(command, args, { shell: false, stdio: 'ignore', windowsHide: true });
7
- child.once('error', () => resolve(false));
8
- child.once('exit', (code) => resolve(code === 0));
9
- });
10
- }
11
6
  /** Checks only whether the platform credential service can be invoked. */
12
7
  export async function credentialStoreStatus() {
13
8
  if (process.platform === 'darwin') {
14
- const available = await executableAvailable('security', ['help']);
15
- return { available, provider: 'macos-keychain', remediation: available ? null : 'Restore the macOS security command before interactive sign-in.' };
9
+ const probe = await credentialProbe('security', ['help']);
10
+ return { ...probe, provider: 'macos-keychain', remediation: probe.available ? null : 'Restore the macOS security command before interactive sign-in.' };
16
11
  }
17
12
  if (process.platform === 'win32') {
18
- const available = await executableAvailable('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]']);
19
- return { available, provider: 'windows-password-vault', remediation: available ? null : 'Use Windows with PowerShell and Password Vault available.' };
13
+ const request = windowsVaultProbe();
14
+ const probe = await credentialProbe(request.command, request.args, request.timeoutMs);
15
+ return { ...probe, provider: 'windows-password-vault', remediation: probe.available ? null : 'Use Windows with PowerShell and Password Vault available.' };
20
16
  }
21
- const available = await executableAvailable('secret-tool', ['--version']);
22
- return { available, provider: 'linux-secret-service', remediation: available ? null : 'Install libsecret tools and start an unlocked Secret Service session, or use a short-lived workload identity in headless automation.' };
17
+ // Global --version/--help are unsupported by libsecret's secret-tool (exit 2).
18
+ // Subcommand help checks the binary without querying or unlocking any secrets.
19
+ const probe = await credentialProbe('secret-tool', ['search', '--help']);
20
+ return { ...probe, provider: 'linux-secret-service', remediation: probe.available ? null : 'Install libsecret tools and start an unlocked Secret Service session, or use a short-lived workload identity in headless automation.' };
23
21
  }
24
22
  async function run(command, args, input, acceptMissing = false) {
25
- return new Promise((resolve, reject) => {
26
- const child = spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
27
- let stdout = '';
28
- let stderr = '';
29
- child.stdout.setEncoding('utf8').on('data', (chunk) => { stdout += chunk; });
30
- child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });
31
- child.on('error', () => reject(new CliError('No supported operating-system credential service is available.', EXIT.auth, 'credential_store_unavailable')));
32
- child.on('close', (code) => {
33
- if (code === 0)
34
- resolve(stdout.trim());
35
- else if (acceptMissing)
36
- resolve('');
37
- else
38
- reject(new CliError(`The operating-system credential service rejected the request${stderr.trim() ? `: ${stderr.trim()}` : '.'}`, EXIT.auth, 'credential_store_failed'));
39
- });
40
- if (input !== undefined)
41
- child.stdin.end(input);
42
- else
43
- child.stdin.end();
23
+ return credentialCommand(command, args, {
24
+ ...(input !== undefined ? { input } : {}),
25
+ ...(acceptMissing ? { missing: {
26
+ code: process.platform === 'darwin' ? 44 : process.platform === 'win32' ? 2 : 1,
27
+ requireEmptyStderr: process.platform !== 'darwin',
28
+ } } : {}),
44
29
  });
45
30
  }
46
- function windowsScript(action, profile) {
47
- const safeProfile = profile.replace(/'/g, "''");
48
- const prefix = `$r='${SERVICE}';$u='${safeProfile}';$v=[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime];`;
49
- if (action === 'get')
50
- return `${prefix}try{$c=(New-Object Windows.Security.Credentials.PasswordVault).Retrieve($r,$u);$c.RetrievePassword();[Console]::Out.Write($c.Password)}catch{exit 2}`;
51
- if (action === 'delete')
52
- return `${prefix}try{$p=New-Object Windows.Security.Credentials.PasswordVault;$c=$p.Retrieve($r,$u);$p.Remove($c)}catch{};`;
53
- return `${prefix}$s=[Console]::In.ReadToEnd();$p=New-Object Windows.Security.Credentials.PasswordVault;try{$c=$p.Retrieve($r,$u);$p.Remove($c)}catch{};$p.Add((New-Object Windows.Security.Credentials.PasswordCredential($r,$u,$s)));`;
31
+ async function windowsCredential(action, profile, token) {
32
+ const request = windowsVaultCommand(action, profile, token);
33
+ return run(request.command, request.args, request.input, action !== 'set');
34
+ }
35
+ async function linuxCredentialExists(profile) {
36
+ // lookup/clear may silently return "not found" when unlocking was cancelled.
37
+ // Search without --unlock also sees locked items. Keep the result private and
38
+ // bounded; a concurrent replacement must not be reported as a successful delete.
39
+ return Boolean(await credentialCommand('secret-tool', ['search', 'service', SERVICE, 'profile', profile], {
40
+ timeoutMs: 5000, missing: { code: 1, requireEmptyStderr: true },
41
+ }));
42
+ }
43
+ function inaccessibleCredential() {
44
+ return new CliError('The saved CLI credential is inaccessible or changed during this request. Unlock your keyring and try again. Review CLI sessions in BlinkHost settings if you need to revoke access.', EXIT.auth, 'credential_store_failed');
54
45
  }
55
46
  export async function getRefreshCredential(profile) {
56
47
  if (process.platform === 'darwin')
57
48
  return (await run('security', ['find-generic-password', '-s', SERVICE, '-a', profile, '-w'], undefined, true)) || null;
58
49
  if (process.platform === 'win32')
59
- return (await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', windowsScript('get', profile)], undefined, true)) || null;
60
- return (await run('secret-tool', ['lookup', 'service', SERVICE, 'profile', profile], undefined, true)) || null;
50
+ return (await windowsCredential('get', profile)) || null;
51
+ const value = await run('secret-tool', ['lookup', 'service', SERVICE, 'profile', profile], undefined, true);
52
+ if (value)
53
+ return value;
54
+ if (await linuxCredentialExists(profile))
55
+ throw inaccessibleCredential();
56
+ return null;
61
57
  }
62
58
  export async function setRefreshCredential(profile, token) {
63
59
  if (!token.startsWith('bhr_'))
64
60
  throw new CliError('The server returned an invalid refresh credential.', EXIT.auth, 'invalid_refresh_credential');
65
61
  if (process.platform === 'darwin') {
66
- await run('security', ['add-generic-password', '-U', '-s', SERVICE, '-a', profile, '-w', token]);
62
+ const request = macosKeychainWrite(profile, token);
63
+ await run(request.command, request.args, request.input);
67
64
  return;
68
65
  }
69
66
  if (process.platform === 'win32') {
70
- await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', windowsScript('set', profile)], token);
67
+ await windowsCredential('set', profile, token);
71
68
  return;
72
69
  }
73
70
  await run('secret-tool', ['store', '--label=BlinkHost CLI', 'service', SERVICE, 'profile', profile], token);
@@ -78,9 +75,11 @@ export async function deleteRefreshCredential(profile) {
78
75
  return;
79
76
  }
80
77
  if (process.platform === 'win32') {
81
- await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', windowsScript('delete', profile)], undefined, true);
78
+ await windowsCredential('delete', profile);
82
79
  return;
83
80
  }
84
81
  await run('secret-tool', ['clear', 'service', SERVICE, 'profile', profile], undefined, true);
82
+ if (await linuxCredentialExists(profile))
83
+ throw inaccessibleCredential();
85
84
  }
86
85
  //# sourceMappingURL=credentials.js.map
@@ -0,0 +1,24 @@
1
+ import { publicRequest } from './api.js';
2
+ type DevicePolling = {
3
+ device_code: string;
4
+ expires_in: number;
5
+ interval: number;
6
+ };
7
+ type DeviceAuthorization = DevicePolling & {
8
+ user_code: string;
9
+ verification_uri_complete: string;
10
+ };
11
+ type PollingServices = {
12
+ request: typeof publicRequest;
13
+ now: () => number;
14
+ sleep: (milliseconds: number) => Promise<void>;
15
+ };
16
+ /** Validate the server contract before displaying terminal text or launching a browser. */
17
+ export declare function validateDeviceAuthorization(data: unknown): DeviceAuthorization;
18
+ export declare function validateDeviceTokens(data: unknown): {
19
+ access_token: string;
20
+ refresh_token: string;
21
+ };
22
+ /** Pending authorization is safe to poll; token delivery and network failures are not retried. */
23
+ export declare function pollDeviceAuthorization(apiOrigin: string, device: DevicePolling, verifier: string, dependencies?: PollingServices): Promise<unknown>;
24
+ export {};
@@ -0,0 +1,76 @@
1
+ import { publicRequest } from './api.js';
2
+ import { CliError, EXIT } from './errors.js';
3
+ const services = {
4
+ request: publicRequest,
5
+ now: () => performance.now(),
6
+ sleep: milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)),
7
+ };
8
+ function expired() {
9
+ throw new CliError('This sign-in code has expired. Run `blinkhost auth login` again to get a new code.', EXIT.auth, 'authorization_expired');
10
+ }
11
+ function validatePolling(device) {
12
+ if (!device || typeof device.device_code !== 'string' || !device.device_code || device.device_code.length > 4096
13
+ || !Number.isSafeInteger(device.expires_in) || device.expires_in < 1 || device.expires_in > 3600
14
+ || !Number.isSafeInteger(device.interval) || device.interval < 1 || device.interval > 60) {
15
+ throw new CliError('BlinkHost returned an invalid sign-in request. No authorization checks were sent.', EXIT.auth, 'authorization_response_invalid');
16
+ }
17
+ }
18
+ /** Validate the server contract before displaying terminal text or launching a browser. */
19
+ export function validateDeviceAuthorization(data) {
20
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
21
+ throw new CliError('BlinkHost returned an invalid sign-in request.', EXIT.auth, 'authorization_response_invalid');
22
+ }
23
+ const device = data;
24
+ validatePolling(device);
25
+ // The service's published verification endpoint is fixed, including for custom API profiles.
26
+ // Exact matching also excludes shell metacharacters on Windows and terminal control text.
27
+ if (typeof device.user_code !== 'string' || device.user_code.length !== 9 || !/^[A-Z2-9]{4}-[A-Z2-9]{4}$/.test(device.user_code)
28
+ || device.verification_uri_complete !== `https://app.blinkhost.me/cli/authorize?code=${device.user_code}`) {
29
+ throw new CliError('BlinkHost returned an invalid sign-in address or code. No browser was opened.', EXIT.auth, 'authorization_response_invalid');
30
+ }
31
+ return device;
32
+ }
33
+ export function validateDeviceTokens(data) {
34
+ const tokens = data;
35
+ if (!tokens || typeof tokens !== 'object' || Array.isArray(tokens)
36
+ || typeof tokens.access_token !== 'string' || !tokens.access_token || tokens.access_token.length > 16384
37
+ || typeof tokens.refresh_token !== 'string' || tokens.refresh_token.trim() !== tokens.refresh_token
38
+ || !/^bhr_[A-Za-z0-9_-]{32,256}$/.test(tokens.refresh_token)) {
39
+ throw new CliError('BlinkHost returned an invalid sign-in session. No new credential was saved.', EXIT.auth, 'authorization_response_invalid');
40
+ }
41
+ return { access_token: tokens.access_token, refresh_token: tokens.refresh_token };
42
+ }
43
+ /** Pending authorization is safe to poll; token delivery and network failures are not retried. */
44
+ export async function pollDeviceAuthorization(apiOrigin, device, verifier, dependencies = services) {
45
+ validatePolling(device);
46
+ const deadline = dependencies.now() + device.expires_in * 1000;
47
+ let interval = Math.max(device.interval, 5) * 1000;
48
+ while (dependencies.now() < deadline) {
49
+ await dependencies.sleep(Math.min(interval, Math.max(0, deadline - dependencies.now())));
50
+ if (dependencies.now() >= deadline)
51
+ return expired();
52
+ const polled = await dependencies.request(apiOrigin, '/api/cli/v2/device/poll/', {
53
+ method: 'POST', body: JSON.stringify({ device_code: device.device_code, code_verifier: verifier }),
54
+ });
55
+ const data = polled.data;
56
+ const code = data && typeof data === 'object' && typeof data.error === 'string'
57
+ ? data.error : '';
58
+ if (!polled.response.ok) {
59
+ if (code === 'authorization_pending')
60
+ continue;
61
+ // OAuth device-flow slow_down increases this and every subsequent interval.
62
+ if (code === 'slow_down') {
63
+ interval += 5000;
64
+ continue;
65
+ }
66
+ if (code === 'expired_token')
67
+ return expired();
68
+ if (code === 'access_denied')
69
+ throw new CliError('CLI authorization was denied. No new session was saved.', EXIT.auth, 'access_denied');
70
+ throw new CliError('CLI authorization could not be completed. Run `blinkhost auth login` to start a new sign-in.', EXIT.auth, 'authorization_failed');
71
+ }
72
+ return data;
73
+ }
74
+ return expired();
75
+ }
76
+ //# sourceMappingURL=device-flow.js.map
@@ -8,7 +8,7 @@ export interface DocumentationTopic {
8
8
  related: string[];
9
9
  url: string;
10
10
  }
11
- export declare const TOP_LEVEL_COMMANDS: ("plugins" | "profile" | "modules" | "dev" | "databases" | "secrets" | "manifest" | "projects" | "repositories" | "connections" | "previews" | "builds" | "deployments" | "bindings" | "assets" | "organizations" | "templates" | "approvals" | "handoffs" | "policies" | "workloads" | "create" | "update" | "quickstart" | "init" | "doctor" | "auth" | "validate" | "test" | "ci" | "functions" | "logs" | "support" | "metrics" | "analytics" | "completion" | "api" | "docs")[];
11
+ export declare const TOP_LEVEL_COMMANDS: ("plugins" | "profile" | "modules" | "dev" | "databases" | "secrets" | "manifest" | "projects" | "repositories" | "connections" | "previews" | "builds" | "deployments" | "bindings" | "assets" | "organizations" | "templates" | "approvals" | "handoffs" | "policies" | "workloads" | "create" | "update" | "ai" | "auth" | "quickstart" | "init" | "doctor" | "validate" | "test" | "ci" | "functions" | "logs" | "support" | "metrics" | "analytics" | "completion" | "api" | "docs")[];
12
12
  export declare function documentationIndex(): {
13
13
  schema: string;
14
14
  cli_version: string;