@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/CHANGELOG.md +177 -0
- package/README.md +252 -6
- package/dist/api.d.ts +5 -0
- package/dist/api.js +165 -5
- package/dist/assistant.d.ts +7 -0
- package/dist/assistant.js +460 -0
- package/dist/auth.d.ts +1 -0
- package/dist/auth.js +22 -29
- package/dist/cli.js +18 -8
- package/dist/compatibility.d.ts +1 -0
- package/dist/compatibility.js +43 -0
- package/dist/credential-lock.d.ts +3 -0
- package/dist/credential-lock.js +52 -0
- package/dist/credential-process.d.ts +19 -0
- package/dist/credential-process.js +75 -0
- package/dist/credentials.d.ts +4 -0
- package/dist/credentials.js +45 -46
- package/dist/device-flow.d.ts +24 -0
- package/dist/device-flow.js +76 -0
- package/dist/guidance.d.ts +1 -1
- package/dist/guidance.js +67 -4
- package/dist/macos-keychain-input.d.ts +6 -0
- package/dist/macos-keychain-input.js +22 -0
- package/dist/module-build.d.ts +7 -0
- package/dist/module-build.js +37 -0
- package/dist/peer-review.d.ts +8 -0
- package/dist/peer-review.js +55 -0
- package/dist/project-export.d.ts +1 -0
- package/dist/project-export.js +79 -0
- package/dist/research.d.ts +1 -0
- package/dist/research.js +42 -0
- package/dist/starter.d.ts +11 -0
- package/dist/starter.js +45 -0
- package/dist/terminal.d.ts +2 -0
- package/dist/terminal.js +12 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/windows-vault-command.d.ts +12 -0
- package/dist/windows-vault-command.js +42 -0
- package/package.json +1 -1
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
|
|
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 (
|
|
95
|
-
|
|
96
|
-
|
|
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
|
+
}>;
|