@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.
package/dist/api.js CHANGED
@@ -1,9 +1,61 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { activeProfile, writeConfig } from './config.js';
3
3
  import { deleteRefreshCredential, getRefreshCredential, setRefreshCredential } from './credentials.js';
4
+ import { withCredentialLock } from './credential-lock.js';
5
+ import { validateDeviceTokens } from './device-flow.js';
4
6
  import { CliError, EXIT } from './errors.js';
5
7
  import { VERSION } from './version.js';
6
8
  const REQUEST_TIMEOUT_MS = 30_000;
9
+ // Only locally written guidance may reach terminal output. Never echo server
10
+ // details, filenames or arbitrary codes from a source-export error response.
11
+ const EXPORT_GUIDANCE = {
12
+ project_template_unsupported: { status: 400, message: 'Portable export needs a supported frontend configuration. Backend-only projects can use projects export PROJECT_UUID --source-only --output ./source.zip to download source without generating or validating build configuration. This command has not changed your source.' },
13
+ committed_secret_detected: { status: 409, message: 'Source export was blocked by credential screening. Review possible credentials in your project before sharing it, and rotate any exposed values. Do not paste credentials into a support request.' },
14
+ html_package_invalid: { status: 409, message: 'Source export could not read the HTML project package configuration. Check that package.json is valid JSON and its scripts field is an object.' },
15
+ dependency_lockfile_missing: { status: 409, message: 'Source export needs package-lock.json for this HTML project. Review the project dependencies, then use its normal dependency-install workflow to create the lockfile. This command has not installed or run anything.' },
16
+ };
17
+ async function exportErrorGuidance(response) {
18
+ const limit = 8192;
19
+ if (![400, 409].includes(response.status)
20
+ || response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json'
21
+ || !response.body)
22
+ return;
23
+ const length = response.headers.get('content-length');
24
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > limit))
25
+ return;
26
+ const reader = response.body.getReader();
27
+ try {
28
+ let size = 0;
29
+ const chunks = [];
30
+ while (true) {
31
+ const chunk = await reader.read();
32
+ if (chunk.done)
33
+ break;
34
+ size += chunk.value.byteLength;
35
+ if (size > limit)
36
+ return;
37
+ chunks.push(Buffer.from(chunk.value));
38
+ }
39
+ if (length !== null && Number(length) !== size)
40
+ return;
41
+ const payload = JSON.parse(Buffer.concat(chunks, size).toString('utf8'));
42
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
43
+ return;
44
+ const code = payload.code;
45
+ if (typeof code !== 'string' || !Object.hasOwn(EXPORT_GUIDANCE, code))
46
+ return;
47
+ const guidance = EXPORT_GUIDANCE[code];
48
+ if (guidance.status === response.status)
49
+ return { code, message: guidance.message };
50
+ }
51
+ catch {
52
+ // Malformed, incomplete and failed error bodies retain the generic HTTP error.
53
+ }
54
+ finally {
55
+ await reader.cancel().catch(() => undefined);
56
+ reader.releaseLock();
57
+ }
58
+ }
7
59
  function messageFrom(payload, fallback) {
8
60
  if (payload && typeof payload === 'object') {
9
61
  const candidate = payload;
@@ -29,11 +81,15 @@ export async function publicRequest(apiOrigin, path, init = {}) {
29
81
  const controller = new AbortController();
30
82
  const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
31
83
  try {
84
+ // Headers are case-insensitive. Object-spreading normalized caller headers
85
+ // into mixed-case defaults makes fetch combine Content-Type values.
86
+ const headers = new Headers({ Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': `BlinkHost-CLI/${VERSION}` });
87
+ new Headers(init.headers).forEach((value, name) => headers.set(name, value));
32
88
  const response = await fetch(new URL(path, `${apiOrigin}/`), {
33
89
  ...init,
34
90
  redirect: 'error',
35
91
  signal: controller.signal,
36
- headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': `BlinkHost-CLI/${VERSION}`, ...Object.fromEntries(new Headers(init.headers).entries()) },
92
+ headers,
37
93
  });
38
94
  return { response, data: await parseResponse(response) };
39
95
  }
@@ -86,23 +142,127 @@ export class ApiClient {
86
142
  throw new CliError(payload.detail || 'BlinkHost rejected this workload identity.', EXIT.auth, 'ci_exchange_failed');
87
143
  return new ApiClient(selected.name, selected.profile, payload.access_token, true);
88
144
  }
145
+ if (process.env.BLINKHOST_REFRESH_TOKEN)
146
+ return ApiClient.refresh(selected);
147
+ return withCredentialLock(selected.name, () => ApiClient.refresh(selected));
148
+ }
149
+ // Caller holds the profile lock for saved credentials. Explicit environment
150
+ // credentials remain caller-managed and are never persisted or removed.
151
+ static async refresh(selected) {
89
152
  const refresh = process.env.BLINKHOST_REFRESH_TOKEN || await getRefreshCredential(selected.name);
90
153
  if (!refresh)
91
154
  throw new CliError('Sign in with `blinkhost auth login` or provide BLINKHOST_ACCESS_TOKEN for CI.', EXIT.auth, 'not_authenticated');
92
155
  const result = await publicRequest(selected.profile.apiOrigin, '/api/cli/v2/token/refresh/', { method: 'POST', body: JSON.stringify({ refresh_token: refresh, client_version: VERSION }) });
93
156
  if (!result.response.ok) {
94
- if (!process.env.BLINKHOST_REFRESH_TOKEN)
95
- await deleteRefreshCredential(selected.name);
96
- throw new CliError(messageFrom(result.data, 'Your CLI session has expired. Sign in again.'), EXIT.auth, 'session_expired');
157
+ if (result.response.status === 401) {
158
+ if (!process.env.BLINKHOST_REFRESH_TOKEN)
159
+ await deleteRefreshCredential(selected.name);
160
+ throw new CliError(messageFrom(result.data, 'Your CLI session has expired. Sign in again.'), EXIT.auth, 'session_expired');
161
+ }
162
+ throw new CliError('BlinkHost could not refresh this session. The saved credential was preserved.', EXIT.network, 'session_refresh_failed');
97
163
  }
98
- const tokens = result.data;
164
+ const tokens = validateDeviceTokens(result.data);
99
165
  if (!process.env.BLINKHOST_REFRESH_TOKEN)
100
166
  await setRefreshCredential(selected.name, tokens.refresh_token);
101
167
  return new ApiClient(selected.name, selected.profile, tokens.access_token, Boolean(process.env.BLINKHOST_REFRESH_TOKEN));
102
168
  }
169
+ static async logout(profileName) {
170
+ const selected = await activeProfile(profileName);
171
+ if (process.env.BLINKHOST_ACCESS_TOKEN || process.env.BLINKHOST_REFRESH_TOKEN
172
+ || (process.env.ACTIONS_ID_TOKEN_REQUEST_URL && process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)) {
173
+ const client = await ApiClient.create(selected.name);
174
+ await client.request('/api/cli/v2/sessions/current/', { method: 'DELETE' });
175
+ return { profile: selected.name };
176
+ }
177
+ return withCredentialLock(selected.name, async () => {
178
+ try {
179
+ const client = await ApiClient.refresh(selected);
180
+ await client.request('/api/cli/v2/sessions/current/', { method: 'DELETE' });
181
+ }
182
+ catch (error) {
183
+ if (!(error instanceof CliError) || error.code !== 'session_expired')
184
+ throw error;
185
+ }
186
+ await deleteRefreshCredential(selected.name);
187
+ return { profile: selected.name };
188
+ });
189
+ }
103
190
  static fromAccessToken(profileName, profile, accessToken) {
104
191
  return new ApiClient(profileName, profile, accessToken, true);
105
192
  }
193
+ async projectArchive(projectId, mode = 'portable') {
194
+ if (!/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(projectId)) {
195
+ throw new CliError('A valid project UUID is required.', EXIT.usage, 'invalid_project_id');
196
+ }
197
+ if (mode !== 'portable' && mode !== 'source')
198
+ throw new CliError('Choose portable or source export mode.', EXIT.usage, 'export_mode_invalid');
199
+ const controller = new AbortController();
200
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
201
+ const requestId = randomUUID();
202
+ const limit = 32 * 1024 * 1024;
203
+ let reader;
204
+ try {
205
+ const response = await fetch(new URL(`/api/source-control/connections/project-export/?project=${projectId}${mode === 'source' ? '&mode=source' : ''}`, this.profile.apiOrigin), {
206
+ method: 'GET', redirect: 'error', signal: controller.signal,
207
+ // Allow the API's JSON error renderer during content negotiation.
208
+ // Successful responses must still pass ZIP-only validation below.
209
+ headers: { Accept: 'application/zip, application/json', Authorization: `Bearer ${this.accessToken}`,
210
+ 'X-Request-ID': requestId, 'User-Agent': `BlinkHost-CLI/${VERSION}` },
211
+ });
212
+ if (!response.ok) {
213
+ const guidance = await exportErrorGuidance(response);
214
+ throw new CliError(guidance?.message || `Project export returned HTTP ${response.status}. Check your access and the project's export status in BlinkHost.`, [401, 403].includes(response.status) ? EXIT.auth : response.status === 409 ? EXIT.conflict : EXIT.remote, `api_${response.status}`, [`Request ID: ${requestId}`, ...(guidance ? [`Export reason: ${guidance.code}`] : [])]);
215
+ }
216
+ // An older API may ignore an unknown query parameter. Never silently
217
+ // save generated configuration when an exact source export was requested.
218
+ if (mode === 'source' && response.headers.get('x-blinkhost-export-mode') !== 'source') {
219
+ await response.body?.cancel().catch(() => undefined);
220
+ throw new CliError('The server did not confirm a source-only export. No archive was saved. Check server support before trying again.', EXIT.validation, 'export_mode_unconfirmed');
221
+ }
222
+ const length = response.headers.get('content-length');
223
+ if (response.status !== 200 || response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/zip'
224
+ || (length !== null && (!/^\d+$/.test(length) || Number(length) > limit)) || !response.body) {
225
+ throw new CliError('The export did not return a supported ZIP archive (maximum 32 MiB).', EXIT.validation, 'invalid_project_archive');
226
+ }
227
+ reader = response.body.getReader();
228
+ const chunks = [];
229
+ let size = 0;
230
+ while (true) {
231
+ const chunk = await reader.read();
232
+ if (chunk.done)
233
+ break;
234
+ size += chunk.value.byteLength;
235
+ if (size > limit)
236
+ throw new CliError('The project ZIP exceeds the CLI download limit of 32 MiB.', EXIT.validation, 'archive_too_large');
237
+ chunks.push(Buffer.from(chunk.value));
238
+ }
239
+ const body = Buffer.concat(chunks, size);
240
+ // The canonical exporter writes a single-disk ZIP without an archive
241
+ // comment. Check its closing directory record too, not just the prefix.
242
+ const end = size - 22;
243
+ if ((length !== null && Number(length) !== size) || size < 22 || !['504b0304', '504b0506'].includes(body.subarray(0, 4).toString('hex'))
244
+ || body.subarray(end, end + 4).toString('hex') !== '504b0506'
245
+ || body.readUInt16LE(end + 4) !== 0 || body.readUInt16LE(end + 6) !== 0
246
+ || body.readUInt16LE(end + 8) !== body.readUInt16LE(end + 10)
247
+ || body.readUInt16LE(end + 20) !== 0
248
+ || body.readUInt32LE(end + 12) + body.readUInt32LE(end + 16) !== end) {
249
+ throw new CliError('The export response is not a ZIP archive.', EXIT.validation, 'invalid_project_archive');
250
+ }
251
+ return body;
252
+ }
253
+ catch (error) {
254
+ if (error instanceof CliError)
255
+ throw error;
256
+ const timedOut = controller.signal.aborted;
257
+ throw new CliError(timedOut ? 'The project export timed out. No archive was saved.' : 'The project export could not be downloaded. No archive was saved.', EXIT.network, timedOut ? 'request_timeout' : 'network_error');
258
+ }
259
+ finally {
260
+ controller.abort();
261
+ if (reader)
262
+ await reader.cancel().catch(() => undefined);
263
+ clearTimeout(timeout);
264
+ }
265
+ }
106
266
  async request(path, init = {}) {
107
267
  const headers = new Headers(init.headers);
108
268
  headers.set('Authorization', `Bearer ${this.accessToken}`);
@@ -0,0 +1,7 @@
1
+ export declare function readAssistantRequest(path: string | undefined): Promise<Record<string, unknown>>;
2
+ export declare function readWorkflowPlan(path: string | undefined): Promise<Record<string, unknown>>;
3
+ export declare function readProjectGuidance(path: string | undefined): Promise<string>;
4
+ export declare function runAssistant(input: string[], profile?: string): Promise<{
5
+ message: string;
6
+ data: unknown;
7
+ }>;