@blinkhost/cli 2.4.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
@@ -0,0 +1,3 @@
1
+ export declare function credentialLockPath(profile: string): string;
2
+ /** Serialize the complete read/rotate/save operation across CLI processes. */
3
+ export declare function withCredentialLock<T>(profile: string, operation: () => Promise<T>, timeoutMs?: number): Promise<T>;
@@ -0,0 +1,52 @@
1
+ import { mkdir, open, unlink } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { validateProfileName } from './config.js';
6
+ import { CliError, EXIT } from './errors.js';
7
+ // The OS credential store keys by profile, independently of CONFIG_HOME and
8
+ // API origin. Commands using different config files must therefore share locks.
9
+ export function credentialLockPath(profile) {
10
+ return join(homedir(), '.blinkhost', 'credential-locks', `${validateProfileName(profile)}.lock`);
11
+ }
12
+ /** Serialize the complete read/rotate/save operation across CLI processes. */
13
+ export async function withCredentialLock(profile, operation, timeoutMs = 45_000) {
14
+ const path = credentialLockPath(profile);
15
+ const directory = join(homedir(), '.blinkhost', 'credential-locks');
16
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 45_000) {
17
+ throw new CliError('The CLI credential lock timeout is invalid.', EXIT.internal, 'credential_lock_invalid');
18
+ }
19
+ try {
20
+ await mkdir(directory, { recursive: true, mode: 0o700 });
21
+ }
22
+ catch {
23
+ throw new CliError('The CLI credential lock directory is unavailable.', EXIT.filesystem, 'credential_lock_failed');
24
+ }
25
+ const deadline = performance.now() + timeoutMs;
26
+ let handle;
27
+ while (!handle) {
28
+ try {
29
+ handle = await open(path, 'wx', 0o600);
30
+ }
31
+ catch (error) {
32
+ if (error.code !== 'EEXIST') {
33
+ throw new CliError('The CLI credential lock is unavailable.', EXIT.filesystem, 'credential_lock_failed');
34
+ }
35
+ if (performance.now() >= deadline) {
36
+ // Never steal an old lock based on time alone: a suspended process may
37
+ // still rotate the credential when it resumes. This file has no secrets.
38
+ throw new CliError('Another CLI command holds this profile’s sign-in lock. Let it finish and retry. If it exited unexpectedly, confirm no CLI command is running before removing the lock file.', EXIT.conflict, 'credential_busy', [path]);
39
+ }
40
+ await delay(Math.min(50, Math.max(1, deadline - performance.now())));
41
+ }
42
+ }
43
+ try {
44
+ await handle.writeFile(JSON.stringify({ pid: process.pid, started_at: new Date().toISOString() }) + '\n');
45
+ return await operation();
46
+ }
47
+ finally {
48
+ await handle.close();
49
+ await unlink(path);
50
+ }
51
+ }
52
+ //# sourceMappingURL=credential-lock.js.map
@@ -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;
package/dist/guidance.js CHANGED
@@ -27,6 +27,57 @@ const resource = (name, summary, extra = []) => ({
27
27
  url: DOCUMENTATION_URL,
28
28
  });
29
29
  const TOPICS = {
30
+ ai: {
31
+ name: 'ai', title: 'Idam assistant — limited preview', summary: 'Inspect tasks and explicitly review source proposals through the BlinkHost control plane.',
32
+ usage: ['blinkhost ai start --request @request.json', 'blinkhost ai list --project PROJECT_UUID',
33
+ 'blinkhost ai status|events TASK_UUID', 'blinkhost ai export TASK_UUID [--include-source]', 'blinkhost ai review TASK_UUID [--path src/file.ts]',
34
+ 'blinkhost ai approve TASK_UUID --digest REVIEW_ACTION_DIGEST --confirm TASK_UUID',
35
+ 'blinkhost ai peer-options TASK_UUID --project PROJECT_UUID',
36
+ 'blinkhost ai peer-invite TASK_UUID --project PROJECT_UUID --reviewer USER_ID --digest ACTION_DIGEST --confirm TASK_UUID',
37
+ 'blinkhost ai peer-inbox --project PROJECT_UUID',
38
+ 'blinkhost ai peer-review PEER_UUID --project PROJECT_UUID',
39
+ 'blinkhost ai peer-approve|peer-decline PEER_UUID --project PROJECT_UUID --digest REVIEW_DIGEST --confirm PEER_UUID',
40
+ 'blinkhost ai peer-withdraw TASK_UUID --project PROJECT_UUID --peer PEER_UUID --confirm TASK_UUID',
41
+ 'blinkhost ai rollback-review TASK_UUID', 'blinkhost ai rollback-approve TASK_UUID --digest UNDO_ACTION_DIGEST --confirm TASK_UUID',
42
+ 'blinkhost ai workflow-plan TASK_UUID --maximum-units TOTAL_LIMIT --confirm TASK_UUID',
43
+ 'blinkhost ai workflow-revise WORKFLOW_UUID --request @plan.json --expected-revision VERSION --digest PLAN_DIGEST --confirm WORKFLOW_UUID',
44
+ 'blinkhost ai workflow-approve WORKFLOW_UUID --expected-revision VERSION --digest PLAN_DIGEST --confirm WORKFLOW_UUID',
45
+ 'blinkhost ai workflow-status WORKFLOW_UUID', 'blinkhost ai workflow-cancel WORKFLOW_UUID --confirm WORKFLOW_UUID',
46
+ 'blinkhost ai memory-show --project PROJECT_UUID',
47
+ 'blinkhost ai compatibility --project PROJECT_UUID',
48
+ 'blinkhost ai sources --project PROJECT_UUID',
49
+ 'blinkhost ai memory-save --project PROJECT_UUID --file @guidance.txt --expected-version VERSION --confirm PROJECT_UUID',
50
+ 'blinkhost ai memory-clear --project PROJECT_UUID --expected-version VERSION --confirm PROJECT_UUID',
51
+ 'blinkhost ai cancel TASK_UUID --confirm TASK_UUID',
52
+ 'blinkhost ai resume TASK_UUID --confirm TASK_UUID',
53
+ 'blinkhost ai starters --project PROJECT_UUID',
54
+ 'blinkhost ai starter-review --project PROJECT_UUID --name api --language LANGUAGE_ID --revision SOURCE_REVISION --request-id REQUEST_UUID',
55
+ 'blinkhost ai starter-status REVIEW_UUID --project PROJECT_UUID',
56
+ 'blinkhost ai starter-approve REVIEW_UUID --project PROJECT_UUID --digest ACTION_DIGEST --confirm REVIEW_UUID',
57
+ 'blinkhost ai build-modules --project PROJECT_UUID',
58
+ 'blinkhost ai build-review --project PROJECT_UUID --module MODULE_UUID --revision SOURCE_REVISION --request-id REQUEST_UUID',
59
+ 'blinkhost ai build-status REVIEW_UUID --project PROJECT_UUID',
60
+ 'blinkhost ai build-approve REVIEW_UUID --project PROJECT_UUID --digest ACTION_DIGEST --confirm REVIEW_UUID'],
61
+ details: ['Idam is a limited preview. Availability depends on server rollout, workspace membership and billing limits. Installing the CLI does not grant access or enable a feature. Requests use the BlinkHost control plane.',
62
+ 'starters and starter-status require ai:read. starter-review requires ai:execute and prepares files from the current platform template without saving them. Retain a stable request UUID; use the current revision and language ID from starters. Inspect every returned file before starter-approve (ai:approve), using the exact review UUID and action digest. Saving adds a backend module through normal project limits; it does not overwrite source, call a model, build, commit or publish. Source, permissions, template and policy are checked again. Reviews expire after 15 minutes. Save the review UUID before approval. If the response is lost or invalid, use starter-status with that same UUID; never repeat an uncertain save automatically. A withdrawn template can hide its preview while keeping its historical save receipt. A receipt remains historical after later edits or module deletion and never recreates source. These commands require current Idam access.',
63
+ 'sources requires ai:read and lists reviewed public-document excerpts only; it does not search or fetch the web. In a research-mode request, research_source_ids can select up to four unique IDs from this catalog. Review attribution, capture date and review due date. Source text counts toward the credit estimate; expired or withdrawn sources stop queued work before model dispatch. Inspect status or export for the original excerpts and whether the model referenced each. A citation is not independent verification of a conclusion. Availability has a separate feature gate and is off by default.',
64
+ 'compatibility requires ai:read and reviews saved project declarations without uploads, model calls, credit reservations or code execution. Findings retain manifest paths and dependency sections, with revision and inspection limits. Fixed npm and Python name rules inspect package.json, single-line requirements.txt and static pyproject.toml declarations; aliases, imports, versions and transitives are not resolved. Python runtime, optional and build-system requirements keep distinct labels. Dynamic dependencies and tool-specific overrides need manual review. Python markers/extras are not evaluated; includes, URLs and pip options are not followed. Other manifest formats need manual review. No findings is not a compatibility pass. Development and build-system dependencies do not necessarily run on the backend. WASM-only backend limits still apply. Review metadata before sharing output and rerun after changes. This is not an adaptation, build, test, preview or deployment command.',
65
+ 'Sign in with explicit scopes: auth login --scope ai:read --scope ai:execute --scope ai:approve. account:read is included for session checks. Other scopes must be requested separately when using --scope. Existing sessions do not gain AI permissions automatically. Workload identities cannot use this personal Idam preview, even if their token lists AI scopes.',
66
+ 'Project guidance is optional, private to your own tasks, and sent to the model as unverified user context. memory-show requires ai:read and prints private text to normal output. Review that version before memory-save or memory-clear (ai:execute), using --expected-version and --confirm PROJECT_UUID. Saving uploads one explicitly selected regular UTF-8 text file of at most 4 KiB; symlinks, empty text and unsupported control characters are refused. Keep credentials out; screening is not exhaustive. No automatic write retries: after a timeout or conflict, run memory-show, compare the saved text/version, then decide whether to submit a new write. Guidance never grants permissions, changes hosting support or bypasses billing. Editing or clearing stops queued tasks and later workflow steps using old guidance; already dispatched work can finish. Clearing keeps a version fence and does not erase copies in task history or backups. Project transfers cannot carry guidance into another organization.',
67
+ 'A start request is a regular UTF-8 JSON file of at most 16 KiB containing project_id, client_request_id (stable UUID), prompt, and maximum_units (1–2000); mode and model are optional. Keep credentials out of prompts. Reuse the same file and client_request_id only for a retry of the same request. Choose a new UUID for a new task.',
68
+ 'The preview uses structural metadata by default. To authorize sharing saved workspace files with Azure OpenAI for this task, add source_paths: an array of up to eight unique project-relative paths. Each file must be at most 16 KiB and all selected files at most 24 KiB; the encoded context limit may reduce this. No local files are uploaded and production data is excluded. Review files first: credential screening is not exhaustive. Task status lists the selected paths. Generated source is unverified. It cannot browse, run tests or deploy.',
69
+ 'Review returns annotated diffs and an action_digest bound to the original source. Invisible controls appear as [U+…] markers; newline annotations are also display-only, not an executable patch. JSON output escapes terminal controls without changing decoded values. Approval requires the digest and explicit task confirmation. A changed project, policy, selection or expired review requires fresh review. Saving source neither creates a Git commit nor builds or publishes it.',
70
+ 'rollback-review prepares an undo of the originally saved files. Inspect every restore and delete operation, then use rollback-approve with its new action_digest and --confirm TASK_UUID. Preparing needs ai:execute; applying needs ai:approve. Later edits to affected files block undo; any workspace edit after review requires a fresh review. Reviews expire after 15 minutes. New files are removed only if unchanged and not open for live editing; folders and other files are kept. There is no force option. Original source must still be retained. Undo is source-only: it does not reverse deployments, Git commits or charges. Duplicate approval does not overwrite later edits. Check task status after a timeout; no automatic retries.',
71
+ 'Peer review lets another current owner or administrator with Idam access review selected code. Sharing is optional, but your workspace may require independent approval before Idam source saves. After preparing an ai review, use peer-options to select a named reviewer. peer-invite explicitly shares only the selected before-and-after code, not conversations, other proposed files or tool history. It can replace the current request. Read commands need ai:read; invite, withdraw and decisions need ai:approve and exact confirmation. A review lasts at most 15 minutes and is bound to the source and current permissions. The reviewer uses peer-inbox, then peer-review, then peer-approve or peer-decline with that review_digest. A decision never saves, builds or publishes; the requester must separately approve the source save. Active pending or declined reviews block saving. Withdrawal ends sharing and preserves history; it does not bypass workspace-required review. This policy covers Idam source saves only, not starter creation, builds or deployments; those retain their separate permissions and approvals. After uncertainty refresh the original review, do not retry automatically. Output is private and diffs are display-only, not executable patches. Commands require current Idam access.',
72
+ 'There is no automatic resubmission after a timeout. Use list/status to inspect state. Usage with an unknown outcome remains reserved, including after cancellation.',
73
+ 'blinkhost ai resume TASK_UUID --confirm TASK_UUID requires ai:execute and asks an eligible multi-step task to continue from its saved checkpoint. It preserves the original task, credit limit, active work, retry delays and usage records. It does not restart completed, cancelled, stopped or usage-reconciliation tasks, approve source changes, or increase spending. Current access, project revision and saved guidance must still match. No automatic retries: inspect status after a timeout. This command requires current Idam access.',
74
+ 'Build commands operate on saved WASM backend modules, not unsaved IDE edits or native server frameworks. build-modules and build-status need ai:read. build-review needs ai:execute, a current source revision and a UUID request-id you retain for reconciliation; preparation stores a review only and does not upload source or start compilation. Inspect the saved source, module, source digest, expiry and usage policy. build-approve needs ai:approve, the exact action digest and review confirmation. It requests one normal metered build, including configured overages and duration usage, with no AI credits. It never promotes an artifact, commits source or publishes. After a timeout use build-status with the same review ID; never start another review to retry an uncertain build. Approvals expire after 15 minutes and source, access, compiler availability and current policy are rechecked. A successful receipt is not a successful compilation; inspect the build state and IDE diagnostics. Commands require current Idam access.',
75
+ 'Connected reviews require a separate feature gate. For an existing plan, diagnose or review task, inspect its maximum_units using status, then workflow-plan with a total limit covering that original cap plus 160 credits (80 for investigation, 80 for review), at most 2000 total. workflow-start is a compatibility alias: it now saves a draft, never approves it. The original task continues independently. Saving, editing and approving a plan do not grant or reserve additional credits. Each later step rechecks access, source revision and available credits. No builds, tools, source changes or deployment are authorized.',
76
+ 'Inspect workflow-status for the saved steps, limits, plan_revision, plan_digest and version history. workflow-revise accepts a regular UTF-8 JSON file up to 16 KiB with exactly steps, maximum_units and maximum_context_units. Use one to three steps, each with mode (plan, diagnose or review), model (gpt-6-luna, gpt-5.6-terra or gpt-6-sol) and maximum_units (1–2000). The total must cover the original task cap plus all steps, at most 2000; the context limit is 1–393216 conservative units, not measured provider tokens. Pass the inspected revision/digest and exact workflow confirmation to revise or approve. Each changed save creates a new version (up to 100); approval binds the exact saved version. Approved and stopped plans cannot be edited or resumed. After a timeout inspect status before any manual retry; do not reuse stale approval. workflow-status needs ai:read; plan, revise and cancel need ai:execute; workflow-approve needs ai:approve. Plan approval never grants source-write authority. Follow-ups retain the original request and previous draft under their own task retention; removing one does not erase copies in another. Version history keeps metadata, not prompt/source/result bodies. Stopping prevents later steps, not charges for dispatched work.',
77
+ 'export prints a versioned, private task snapshot (blinkhost.idam.task-export/v1) to normal output. Use --json for machine-readable output. Proposed source-file copies require --include-source; input files, internal context, tool receipts and approval tokens are never included. Requests and narrative may still contain private information. Review before sharing. Removed content stays removed, and history above 1,000 events is explicitly marked partial. Downloads are not project backups or proof of deployment, and task-history removal cannot erase existing downloads. Exports over 4 MiB are refused, not silently cut short.'],
78
+ examples: ['blinkhost docs ai', 'blinkhost ai start --request @request.json --json', 'blinkhost ai status TASK_UUID --json'],
79
+ related: ['auth', 'security', 'projects', 'builds'], url: DOCUMENTATION_URL,
80
+ },
30
81
  quickstart: {
31
82
  name: 'quickstart', title: 'Safe first steps', summary: 'Inspect local readiness and receive a non-destructive path to your first BlinkHost project.',
32
83
  usage: ['blinkhost quickstart [path]', 'blinkhost quickstart [path] --json'],
@@ -65,15 +116,27 @@ const TOPICS = {
65
116
  },
66
117
  auth: {
67
118
  name: 'auth', title: 'Authentication and sessions', summary: 'Connect a device through browser approval and manage its CLI sessions.',
68
- usage: ['blinkhost auth login [--no-browser] [--api-origin URL]', 'blinkhost auth status', 'blinkhost auth sessions', 'blinkhost auth revoke SESSION_ID', 'blinkhost auth logout'],
69
- details: ['Passwords are never entered in the terminal. Refresh credentials are stored only in macOS Keychain, Windows Password Vault, or Linux Secret Service through secret-tool.', 'Headless automation should use a registered GitHub OIDC workload or a short-lived BLINKHOST_ACCESS_TOKEN supplied by an approved CI secret service. Never persist it in source or CLI configuration.', '--non-interactive prevents browser authorization and fails closed when interaction would be required.'],
119
+ usage: ['blinkhost auth login [--no-browser] [--api-origin URL] [--scope PERMISSION]', 'blinkhost auth status', 'blinkhost auth sessions', 'blinkhost auth revoke SESSION_ID', 'blinkhost auth logout'],
120
+ details: ['Passwords are never entered in the terminal. Refresh credentials are stored only in macOS Keychain, Windows Password Vault, or Linux Secret Service through secret-tool.',
121
+ 'If your session is rejected after signing out of all devices, an account security change or a BlinkHost security update, run blinkhost auth login again with the same --profile and any explicit --scope options you need. Review and approve the new browser request in the correct account. An old approval link cannot reconnect the CLI. Your project files, deployments and billing plan are unchanged by reauthentication.',
122
+ 'If a fresh sign-in is blocked, check email verification and required legal acceptance in the dashboard. Do not copy credentials from another device to bypass the check.',
123
+ 'Headless automation should use a registered GitHub OIDC workload or a short-lived BLINKHOST_ACCESS_TOKEN supplied by an approved CI secret service. Never persist it in source or CLI configuration.', '--non-interactive prevents browser authorization and fails closed when interaction would be required.'],
70
124
  examples: ['blinkhost auth login', 'blinkhost auth login --no-browser', 'blinkhost auth sessions --json'], related: ['profile', 'ci', 'security', 'portability'], url: DOCUMENTATION_URL,
71
125
  },
72
126
  profile: {
73
127
  name: 'profile', title: 'Account profiles', summary: 'Keep personal and work BlinkHost sessions separate.',
74
128
  usage: ['blinkhost profile list', 'blinkhost profile use NAME'], details: ['--profile NAME selects a profile for one command. BLINKHOST_PROFILE selects a default for the current process. Profile names contain lowercase letters, numbers, hyphens or underscores.'], examples: ['blinkhost auth login --profile work', 'blinkhost profile use work'], related: ['auth', 'security'], url: DOCUMENTATION_URL,
75
129
  },
76
- projects: resource('projects', 'Manage projects and explicit local project links.', ['`projects link PROJECT_ID [path]` writes only a local .blinkhost/project.json pointer and does not change or deploy the remote project.', '`projects unlink [path]` removes only that local pointer. `projects pull|push CONNECTION_ID` synchronizes through a configured source connection.']),
130
+ projects: {
131
+ ...resource('projects', 'Manage projects and explicit local project links.'),
132
+ usage: [...resource('projects', '').usage, 'blinkhost projects export PROJECT_UUID [--source-only] --output ./project.zip'],
133
+ details: [...resource('projects', '').details,
134
+ 'projects link/unlink manage only the local pointer. projects pull/push synchronize through a configured source connection.',
135
+ 'projects export downloads a source ZIP through the existing project export service. Requires projects:read and an owner, admin or developer role. A GitHub connection is not required.',
136
+ 'Default portable export requires a supported frontend configuration. Use --source-only for backend-only projects or to preserve source without generating or validating build configuration, READMEs, database schemas or lockfiles. Existing files and validated project assets are retained; a connected repository uses its saved base with workspace changes, not a fresh remote fetch. The server must confirm source-only mode. Both modes enforce the same authorization and screening; neither changes stored source.',
137
+ 'The CLI accepts archives up to 32 MiB, never overwrites files, follows no download redirects, and does not extract or run source. Use a new .zip path in an existing directory without symbolic links. The file is private to your account where POSIX permissions apply.',
138
+ 'This exports source and portable configuration, not database rows, runtime secret values, deployed artifacts or complete Git history. Review before sharing: secret screening is not a guarantee. Recreate bindings and resources separately and validate runtime compatibility at the destination. ai export is a separate task-history snapshot.'],
139
+ },
77
140
  repositories: resource('repositories', 'Inspect and manage connected source repositories.'),
78
141
  connections: resource('connections', 'Manage project-to-repository source connections.'),
79
142
  previews: resource('previews', 'Manage temporary preview environments.', ['`previews wait ID [--timeout 10..3600]` waits for a terminal state. `previews open ID` accepts only trusted BlinkHost HTTPS preview hosts. Preview operations can consume plan resources.']),
@@ -160,7 +223,7 @@ const TOPICS = {
160
223
  },
161
224
  };
162
225
  const COMMANDS = [
163
- 'quickstart', 'docs', 'create', 'init', 'validate', 'manifest', 'doctor', 'test', 'auth', 'profile', 'projects',
226
+ 'quickstart', 'docs', 'create', 'init', 'validate', 'manifest', 'doctor', 'test', 'auth', 'ai', 'profile', 'projects',
164
227
  'repositories', 'connections', 'previews', 'builds', 'deployments', 'modules', 'functions', 'databases', 'bindings', 'assets',
165
228
  'secrets', 'organizations', 'templates', 'approvals', 'handoffs', 'policies', 'workloads', 'dev', 'logs', 'metrics',
166
229
  'analytics', 'support', 'completion', 'update', 'ci', 'plugins', 'api',
@@ -0,0 +1,6 @@
1
+ /** One command for security's stdin parser, not a shell or process argument. */
2
+ export declare function macosKeychainWrite(profile: string, token: string): {
3
+ command: string;
4
+ args: string[];
5
+ input: string;
6
+ };
@@ -0,0 +1,22 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ /** One command for security's stdin parser, not a shell or process argument. */
3
+ export function macosKeychainWrite(profile, token) {
4
+ if (!/^bhr_[A-Za-z0-9_-]{32,256}$/.test(token)) {
5
+ throw new CliError('The server returned an invalid refresh credential.', EXIT.auth, 'invalid_refresh_credential');
6
+ }
7
+ // Normal CLI profiles are more restrictive. This boundary also handles the
8
+ // quoted synthetic native-vault fixtures without admitting another input line.
9
+ if (!profile || profile.length > 128 || !/^[\x20-\x7e]+$/.test(profile)) {
10
+ throw new CliError('The credential profile is invalid.', EXIT.auth, 'invalid_profile');
11
+ }
12
+ const quote = (value) => `"${value.replace(/["\\]/g, '\\$&')}"`;
13
+ const input = `add-generic-password -U -s blinkhost-cli -a ${quote(profile)} -w ${quote(token)}\n`;
14
+ // Apple's security input buffer is 4096 bytes. Keep newline and NUL inside
15
+ // it. Exactly one line followed by EOF preserves this command's exit status;
16
+ // adding "quit" or a readback command could mask a failed write.
17
+ if (Buffer.byteLength(input, 'utf8') >= 4096) {
18
+ throw new CliError('The credential request is too large.', EXIT.auth, 'credential_store_configuration_invalid');
19
+ }
20
+ return { command: '/usr/bin/security', args: ['-q', '-i'], input };
21
+ }
22
+ //# sourceMappingURL=macos-keychain-input.js.map