@bugb-technologies/bravos 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account.js +41 -5
- package/dist/artifacts.js +23 -10
- package/dist/cli.js +31 -7
- package/dist/device.js +124 -0
- package/dist/guide.js +1 -1
- package/dist/help.js +9 -5
- package/dist/licence.js +6 -3
- package/dist/plugin-release.js +56 -13
- package/dist/setup.js +1 -1
- package/docs/GUIDE.md +1 -1
- package/hooks/lib/autopilot.mjs +3 -22
- package/hooks/lib/briefing.mjs +6 -3
- package/hooks/lib/pre-pr.mjs +1 -1
- package/hooks/lib/proving.mjs +25 -0
- package/hooks/lib/refresh.mjs +203 -0
- package/package.json +1 -1
package/dist/account.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// @comment -- "bravos account: how a licence gets onto this machine. `activate` is the device-code pairing with the account portal (one POST to start, the browser to approve, polling until the portal hands back a signed token); `import` takes a downloaded file. Either way the token is verified by the same offline verifier before it is written, so a token the portal signed with a key this build does not trust is refused here, not at the first gated command. The origin is fixed (BRAVOS_ACCOUNT_ORIGIN overrides it for a local portal), no proxy is read from the environment, and the token is written 0600."
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { hostname } from 'node:os';
|
|
4
5
|
import { join } from 'node:path';
|
|
6
|
+
import { refreshLib, userAgent } from './device.js';
|
|
5
7
|
import { licenceLib, licenceLines } from './licence.js';
|
|
6
8
|
import { BravosError } from './types.js';
|
|
7
9
|
export const ACTIVATION_PATH = '/api/v1/cli/activation';
|
|
@@ -60,7 +62,9 @@ export async function importLicence(path, io) {
|
|
|
60
62
|
const L = await licenceLib();
|
|
61
63
|
return [`Licence written to ${file}`, ...licenceLines(L, status)];
|
|
62
64
|
}
|
|
63
|
-
|
|
65
|
+
/** What this machine calls itself in the portal's device list: the host name, printable ASCII only, at most 64 characters. */
|
|
66
|
+
export const deviceName = (raw = hostname()) => raw.replace(/[^\x20-\x7e]/g, '').trim().slice(0, 64) || 'unnamed machine';
|
|
67
|
+
// @comment -- "The device-code flow: POST /api/v1/cli/activation (body: this machine's name and refresh: true, which asks the portal for a short-lived per-machine token this build keeps current), show the code and open the verification URL, then poll /api/v1/cli/activation/poll with the device code as a bearer until the portal answers 200 {license} (428 pending, 429 slow down, 410 expired or consumed, 402 trial ended, 403 no licence assigned to this person or the machine limit reached). The device code never goes anywhere but that origin, and the token it yields is verified before it is written. When the token is a device token (a `did` claim), the device code becomes this machine's refresh secret and is kept in device.json (0600) beside the licence."
|
|
64
68
|
export async function activate(io) {
|
|
65
69
|
const L = await licenceLib();
|
|
66
70
|
const origin = accountOrigin(io.env, L);
|
|
@@ -68,10 +72,10 @@ export async function activate(io) {
|
|
|
68
72
|
const sleep = io.sleep ?? ((s) => new Promise((r) => setTimeout(r, s * 1000)));
|
|
69
73
|
const now = io.now ?? (() => Date.now() / 1000);
|
|
70
74
|
const open = io.open ?? defaultOpen;
|
|
71
|
-
const ua = { 'User-Agent':
|
|
75
|
+
const ua = { 'User-Agent': userAgent(), Accept: 'application/json' };
|
|
72
76
|
let start;
|
|
73
77
|
try {
|
|
74
|
-
const r = await f(`${origin}${ACTIVATION_PATH}`, { method: 'POST', headers: { ...ua, 'Content-Type': 'application/json' }, body:
|
|
78
|
+
const r = await f(`${origin}${ACTIVATION_PATH}`, { method: 'POST', headers: { ...ua, 'Content-Type': 'application/json' }, body: JSON.stringify({ device_name: deviceName(), refresh: true }) });
|
|
75
79
|
if (r.status === 404 || r.status === 405)
|
|
76
80
|
throw new BravosError(`${origin} does not offer CLI sign-in yet; download the licence from ${L.ACCOUNT_LICENCES} and run bravos account import <file>`);
|
|
77
81
|
if (!r.ok)
|
|
@@ -129,12 +133,44 @@ export async function activate(io) {
|
|
|
129
133
|
}
|
|
130
134
|
throw new BravosError(`this account's Team trial has ended and it has no plan, so no licence was written; this machine stays on Free (the research loop keeps working). Choose a plan at ${upgrade}, then run bravos account activate again`);
|
|
131
135
|
}
|
|
136
|
+
// 403: the person was signed in but the portal will not license this machine for them. Nothing is written.
|
|
137
|
+
if (r.status === 403) {
|
|
138
|
+
let error = null;
|
|
139
|
+
let manage = `${origin}/dashboard/license`;
|
|
140
|
+
try {
|
|
141
|
+
const b = (await r.json());
|
|
142
|
+
error = b?.error;
|
|
143
|
+
if (typeof b?.manage === 'string' && b.manage.startsWith(origin + '/'))
|
|
144
|
+
manage = b.manage;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
/* the default page */
|
|
148
|
+
}
|
|
149
|
+
if (error === 'device_limit')
|
|
150
|
+
throw new BravosError(`you already have the most machines your account allows, so no licence was written; remove one at ${manage} (or run bravos account devices / bravos account revoke <id> on a machine that is signed in), then run bravos account activate again`);
|
|
151
|
+
if (error === 'licence_not_assigned')
|
|
152
|
+
throw new BravosError(`you do not hold a licence on your team's account yet, so no licence was written; this machine stays on Free. Ask an owner or admin to assign you one, or request it at ${manage}, then run bravos account activate again`);
|
|
153
|
+
throw new BravosError(`${origin} refused to license this machine (HTTP 403${typeof error === 'string' ? `: ${error}` : ''}); see ${manage}`);
|
|
154
|
+
}
|
|
132
155
|
if (!r.ok)
|
|
133
156
|
throw new BravosError(`${origin} answered HTTP ${r.status} while waiting; run bravos account activate again`);
|
|
134
157
|
const body = (await r.json());
|
|
135
158
|
if (typeof body?.license !== 'string')
|
|
136
159
|
throw new BravosError(`${origin} approved the code but sent no licence; download it from ${L.ACCOUNT_LICENCES} and run bravos account import <file>`);
|
|
137
160
|
const { file, status } = await installToken(body.license, io.env, origin);
|
|
138
|
-
|
|
161
|
+
const lines = [`Licence written to ${file}`, ...licenceLines(L, status)];
|
|
162
|
+
const R = await refreshLib();
|
|
163
|
+
const did = R.claimsOf(body.license.trim())?.did;
|
|
164
|
+
if (typeof did === 'string' && R.isDeviceSecret(start.device_code)) {
|
|
165
|
+
R.writeDevice(io.env, { origin, device_id: R.isDeviceId(did) ? did : null, device_secret: start.device_code });
|
|
166
|
+
lines.push(`This machine is signed in to ${origin}; bravos renews its licence automatically. bravos account devices lists your machines, bravos account logout signs this one out.`);
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
// A licence that is not a device token (a trial, or an older portal) is not renewed; a stale device record would point at the wrong licence.
|
|
170
|
+
const stale = R.devicePath(io.env);
|
|
171
|
+
if (stale)
|
|
172
|
+
rmSync(stale, { force: true });
|
|
173
|
+
}
|
|
174
|
+
return lines;
|
|
139
175
|
}
|
|
140
176
|
}
|
package/dist/artifacts.js
CHANGED
|
@@ -4,6 +4,7 @@ import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readd
|
|
|
4
4
|
import { arch, platform } from 'node:os';
|
|
5
5
|
import { dirname, join } from 'node:path';
|
|
6
6
|
import { gunzipSync } from 'node:zlib';
|
|
7
|
+
import { refresh, userAgent } from './device.js';
|
|
7
8
|
import { licenceLib } from './licence.js';
|
|
8
9
|
import { BravosError } from './types.js';
|
|
9
10
|
import { ANALYZER_VERSION, CODEGRAPH_VERSION } from './versions.js';
|
|
@@ -330,7 +331,7 @@ async function get(f, url, limit, what, headers = {}) {
|
|
|
330
331
|
throw new BravosError(`the ${what} is ${buf.length} bytes, past the ${limit}-byte ceiling (${url.split('?')[0]})`);
|
|
331
332
|
return buf;
|
|
332
333
|
}
|
|
333
|
-
// @comment -- "Where the files come from. With BRAVOS_ARTIFACT_BASE_URL, a plain layout <base>/<kind>/<version>/<file> (tests, mirrors). Otherwise the account portal: GET /api/v1/cli/artifacts/<kind>/<version>/<triple> with the licence as the bearer; the portal verifies it, counts the pull, and answers presigned URLs into the private bucket. The licence token goes to the portal origin and nowhere else; the presigned URLs carry their own authorization."
|
|
334
|
+
// @comment -- "Where the files come from. With BRAVOS_ARTIFACT_BASE_URL, a plain layout <base>/<kind>/<version>/<file> (tests, mirrors). Otherwise the account portal: GET /api/v1/cli/artifacts/<kind>/<version>/<triple> with the licence as the bearer; the portal verifies it (and, for a device or CI licence, that it has not been revoked), counts the pull, and answers presigned URLs into the private bucket. On 401 or 403 a device licence is renewed once and the request repeated once. The licence token goes to the portal origin and nowhere else; the presigned URLs carry their own authorization."
|
|
334
335
|
async function urlsFor(kind, version, target, io) {
|
|
335
336
|
const f = io.fetch ?? fetch;
|
|
336
337
|
const base = (io.env[BASE_URL_ENV] || '').trim();
|
|
@@ -339,19 +340,31 @@ async function urlsFor(kind, version, target, io) {
|
|
|
339
340
|
return { manifest: `${root}/manifest.json`, manifestSig: `${root}/manifest.json.sig`, artifact: (file) => `${root}/${file}`, artifactSig: (file) => `${root}/${file}.sig` };
|
|
340
341
|
}
|
|
341
342
|
const L = await licenceLib();
|
|
342
|
-
const found = L.find(io.env);
|
|
343
|
-
if (!found.token)
|
|
344
|
-
throw new BravosError(`no licence at ${found.source}: the ${kind} download is licensed — bravos account activate (30-day Team trial, no card)`);
|
|
345
343
|
const originRaw = (io.env.BRAVOS_ACCOUNT_ORIGIN || '').trim();
|
|
346
344
|
const origin = originRaw || L.ACCOUNT_ORIGIN;
|
|
347
345
|
const url = `${origin}/api/v1/cli/artifacts/${kind}/${version}/${target}`;
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
346
|
+
const ask = async () => {
|
|
347
|
+
const found = L.find(io.env);
|
|
348
|
+
if (!found.token)
|
|
349
|
+
throw new BravosError(`no licence at ${found.source}: the ${kind} download is licensed — bravos account activate (30-day Team trial, no card)`);
|
|
350
|
+
try {
|
|
351
|
+
return { found, r: await f(url, { headers: { 'User-Agent': userAgent(), Accept: 'application/json', Authorization: `Bearer ${found.token}` } }) };
|
|
352
|
+
}
|
|
353
|
+
catch (e) {
|
|
354
|
+
throw new BravosError(`could not reach ${origin} for the ${kind} download: ${e.message}`);
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
let { r, found } = await ask();
|
|
358
|
+
// A device licence the portal refuses may only be stale (rotated on another process) or revoked: renew once, and ask once more only when a new token was written.
|
|
359
|
+
if (r.status === 401 || r.status === 403) {
|
|
360
|
+
const renewed = await refresh({ env: io.env, fetch: f }, true);
|
|
361
|
+
if (renewed.outcome === 'refreshed')
|
|
362
|
+
({ r, found } = await ask());
|
|
363
|
+
else if (renewed.outcome === 'revoked' || renewed.outcome === 'lapsed')
|
|
364
|
+
throw new BravosError(`${origin} refused the ${kind} download. ${renewed.note}`);
|
|
354
365
|
}
|
|
366
|
+
if (r.status === 403)
|
|
367
|
+
throw new BravosError(`${origin} refused the ${kind} download: the licence from ${found.source} has been revoked or you no longer hold one (${L.ACCOUNT_LICENCES})`);
|
|
355
368
|
if (r.status === 402)
|
|
356
369
|
throw new BravosError(`${origin} refused the ${kind} download: the licence from ${found.source} does not cover it (${L.ACCOUNT_UPGRADE})`);
|
|
357
370
|
if (r.status === 401)
|
package/dist/cli.js
CHANGED
|
@@ -21,6 +21,7 @@ import { formatDoctor, runDoctor, withLicence } from './doctor.js';
|
|
|
21
21
|
import { ensureGuardlink, registerPrePr, whichBin, writeScope } from './guardlink.js';
|
|
22
22
|
import { installHook } from './hooks.js';
|
|
23
23
|
import { activate, importLicence } from './account.js';
|
|
24
|
+
import { listDevices, logout, refresh as refreshDevice, revokeDevice } from './device.js';
|
|
24
25
|
import * as graph from './codegraph.js';
|
|
25
26
|
import { askGraph } from './watch.js';
|
|
26
27
|
import { plan as setupPlan, runSast, runSetup } from './setup.js';
|
|
@@ -398,22 +399,45 @@ export function buildProgram(io, result) {
|
|
|
398
399
|
lines.push(...licenceLines(L, v));
|
|
399
400
|
}));
|
|
400
401
|
program
|
|
401
|
-
.command('account <action> [
|
|
402
|
-
.description('activate: sign in once in the browser and get this machine its licence (a 30-day Team trial when the account has no plan); import FILE: install a downloaded licence; status: same as bravos licence.')
|
|
403
|
-
.action((action,
|
|
402
|
+
.command('account <action> [arg]')
|
|
403
|
+
.description('activate: sign in once in the browser and get this machine its licence (a 30-day Team trial when the account has no plan); import FILE: install a downloaded licence; status: same as bravos licence; refresh: renew this machine\'s licence now; devices: list your signed-in machines; revoke ID: sign one of them out; logout: sign this machine out and remove its licence.')
|
|
404
|
+
.action((action, arg) => guardedAsync(async (lines) => {
|
|
405
|
+
const accountIo = { env: io.env, stdout: io.stdout };
|
|
404
406
|
if (action === 'activate')
|
|
405
|
-
lines.push(...(await activate(
|
|
407
|
+
lines.push(...(await activate(accountIo)));
|
|
406
408
|
else if (action === 'import') {
|
|
407
|
-
if (!
|
|
409
|
+
if (!arg)
|
|
408
410
|
throw new BravosError('usage: bravos account import <licence file>');
|
|
409
|
-
lines.push(...(await importLicence(resolve(
|
|
411
|
+
lines.push(...(await importLicence(resolve(arg), accountIo)));
|
|
410
412
|
}
|
|
411
413
|
else if (action === 'status') {
|
|
412
414
|
const L = await licenceLib();
|
|
413
415
|
lines.push(...licenceLines(L, L.status(io.env)));
|
|
414
416
|
}
|
|
417
|
+
else if (action === 'refresh') {
|
|
418
|
+
const L = await licenceLib();
|
|
419
|
+
const r = await refreshDevice({ env: io.env }, true);
|
|
420
|
+
if (r.outcome === 'refreshed')
|
|
421
|
+
lines.push('Licence renewed.');
|
|
422
|
+
else if (r.outcome === 'revoked' || r.outcome === 'lapsed')
|
|
423
|
+
lines.push(r.note);
|
|
424
|
+
else if (r.outcome === 'skipped')
|
|
425
|
+
lines.push(r.reason === 'environment' ? 'The licence comes from BRAVOS_LICENCE, which is never renewed here.' : 'This machine has no device licence to renew (bravos account activate signs it in).');
|
|
426
|
+
else
|
|
427
|
+
lines.push('Could not renew the licence just now; the current one keeps working until it expires.');
|
|
428
|
+
lines.push(...licenceLines(L, L.status(io.env)));
|
|
429
|
+
}
|
|
430
|
+
else if (action === 'devices')
|
|
431
|
+
lines.push(...(await listDevices({ env: io.env })));
|
|
432
|
+
else if (action === 'revoke') {
|
|
433
|
+
if (!arg)
|
|
434
|
+
throw new BravosError('usage: bravos account revoke <device id> (bravos account devices lists them)');
|
|
435
|
+
lines.push(...(await revokeDevice({ env: io.env }, arg)));
|
|
436
|
+
}
|
|
437
|
+
else if (action === 'logout')
|
|
438
|
+
lines.push(...(await logout({ env: io.env })));
|
|
415
439
|
else
|
|
416
|
-
throw new BravosError(`unknown account action ${JSON.stringify(action)}: activate, import <file> or
|
|
440
|
+
throw new BravosError(`unknown account action ${JSON.stringify(action)}: activate, import <file>, status, refresh, devices, revoke <id> or logout`);
|
|
417
441
|
}));
|
|
418
442
|
program
|
|
419
443
|
.command('setup')
|
package/dist/device.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// @comment -- "The CLI's side of per-machine licences: a typed wrapper over hooks/lib/refresh.mjs (the one refresh implementation, shared with the session hook), and the three account commands that act on this machine's device record — refresh (force a new token), devices (the person's machines, as the portal lists them) and logout / revoke (end one machine's licence at the portal). Every request goes to the origin stored in device.json at activation, with the device secret as the bearer, and nowhere else."
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { hooksDir, version } from './paths.js';
|
|
5
|
+
import { BravosError } from './types.js';
|
|
6
|
+
let cached = null;
|
|
7
|
+
export const refreshLib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'refresh.mjs')).href));
|
|
8
|
+
export const userAgent = () => `bravos-cli/${version()}`;
|
|
9
|
+
// @comment -- "Refreshes this machine's device licence when it is due (or always, with force). Never throws; the outcome says what happened, and a revocation or a lapsed plan carries the sentence to show."
|
|
10
|
+
export async function refresh(io, force = false) {
|
|
11
|
+
const R = await refreshLib();
|
|
12
|
+
return R.refreshIfDue(io.env, { fetch: io.fetch, now: io.now, force, userAgent: userAgent() });
|
|
13
|
+
}
|
|
14
|
+
const requireDevice = async (env) => {
|
|
15
|
+
const R = await refreshLib();
|
|
16
|
+
const device = R.readDevice(env);
|
|
17
|
+
if (!device)
|
|
18
|
+
throw new BravosError('this machine has no device licence (bravos account activate signs it in); a licence imported from a file or set in BRAVOS_LICENCE has no device record');
|
|
19
|
+
return { R, device };
|
|
20
|
+
};
|
|
21
|
+
const call = async (io, device, path, init) => {
|
|
22
|
+
const f = io.fetch ?? fetch;
|
|
23
|
+
let r;
|
|
24
|
+
try {
|
|
25
|
+
r = await f(`${device.origin}${path}`, {
|
|
26
|
+
...init,
|
|
27
|
+
headers: { 'User-Agent': userAgent(), Accept: 'application/json', Authorization: `Bearer ${device.device_secret}`, ...(init.body ? { 'Content-Type': 'application/json' } : {}) },
|
|
28
|
+
signal: AbortSignal.timeout(10_000),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
throw new BravosError(`could not reach ${device.origin}: ${e.message}`);
|
|
33
|
+
}
|
|
34
|
+
let body = null;
|
|
35
|
+
try {
|
|
36
|
+
body = (await r.json());
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
body = null;
|
|
40
|
+
}
|
|
41
|
+
return { status: r.status, body };
|
|
42
|
+
};
|
|
43
|
+
const refusedLine = (R, status, body) => {
|
|
44
|
+
const error = typeof body?.error === 'string' ? body.error : null;
|
|
45
|
+
if (status === 401)
|
|
46
|
+
return R.revokedNote('invalid_device');
|
|
47
|
+
if (status === 403 && error)
|
|
48
|
+
return R.revokedNote(error);
|
|
49
|
+
return null;
|
|
50
|
+
};
|
|
51
|
+
const day = (iso) => (typeof iso === 'string' && !Number.isNaN(Date.parse(iso)) ? new Date(iso).toISOString().slice(0, 10) : '—');
|
|
52
|
+
// @comment -- "bravos account devices: GET /api/v1/cli/devices with this machine's device secret, printed as a table (name, added, last seen, which one is this machine) with the per-person limit. A refusal that means this machine is no longer licensed is reported, and the local files removed, exactly as a refresh would."
|
|
53
|
+
export async function listDevices(io) {
|
|
54
|
+
const { R, device } = await requireDevice(io.env);
|
|
55
|
+
const { status, body } = await call(io, device, R.DEVICES_PATH, { method: 'GET' });
|
|
56
|
+
const refused = refusedLine(R, status, body);
|
|
57
|
+
if (refused) {
|
|
58
|
+
R.forgetDevice(io.env);
|
|
59
|
+
throw new BravosError(refused);
|
|
60
|
+
}
|
|
61
|
+
if (status !== 200 || !Array.isArray(body?.devices))
|
|
62
|
+
throw new BravosError(`${device.origin} answered HTTP ${status} for the device list`);
|
|
63
|
+
const rows = body.devices.map((d) => ({
|
|
64
|
+
name: typeof d.name === 'string' && d.name ? d.name.slice(0, 64) : '(unnamed)',
|
|
65
|
+
added: day(d.created_at),
|
|
66
|
+
seen: day(d.last_seen_at),
|
|
67
|
+
id: typeof d.id === 'string' ? d.id : '',
|
|
68
|
+
current: d.current === true || (typeof d.id === 'string' && d.id === device.device_id),
|
|
69
|
+
}));
|
|
70
|
+
const limit = typeof body.limit === 'number' ? body.limit : null;
|
|
71
|
+
const lines = [`Your machines (${rows.length}${limit !== null ? ` of ${limit}` : ''}):`];
|
|
72
|
+
const width = Math.max(4, ...rows.map((r) => r.name.length));
|
|
73
|
+
lines.push(` ${'NAME'.padEnd(width)} ADDED LAST SEEN ID`);
|
|
74
|
+
for (const r of rows)
|
|
75
|
+
lines.push(` ${r.name.padEnd(width)} ${r.added.padEnd(10)} ${r.seen.padEnd(10)} ${r.id}${r.current ? ' (this machine)' : ''}`);
|
|
76
|
+
if (rows.length === 0)
|
|
77
|
+
lines.push(' none');
|
|
78
|
+
lines.push('Remove one with bravos account revoke <id>, or this machine with bravos account logout.');
|
|
79
|
+
return lines;
|
|
80
|
+
}
|
|
81
|
+
// @comment -- "bravos account revoke <id>: ends one of the person's other machines at the portal (POST /api/v1/cli/devices/revoke with {device_id}). The id is checked to be a uuid before it is sent; the portal decides whether it is the caller's own."
|
|
82
|
+
export async function revokeDevice(io, deviceId) {
|
|
83
|
+
const { R, device } = await requireDevice(io.env);
|
|
84
|
+
if (!R.isDeviceId(deviceId))
|
|
85
|
+
throw new BravosError(`${JSON.stringify(deviceId)} is not a device id; bravos account devices lists them`);
|
|
86
|
+
if (deviceId === device.device_id)
|
|
87
|
+
return logout(io);
|
|
88
|
+
const { status, body } = await call(io, device, R.REVOKE_PATH, { method: 'POST', body: JSON.stringify({ device_id: deviceId }) });
|
|
89
|
+
if (status === 404)
|
|
90
|
+
throw new BravosError(`${deviceId} is not one of your machines; bravos account devices lists them`);
|
|
91
|
+
const refused = refusedLine(R, status, body);
|
|
92
|
+
if (refused) {
|
|
93
|
+
R.forgetDevice(io.env);
|
|
94
|
+
throw new BravosError(refused);
|
|
95
|
+
}
|
|
96
|
+
if (status !== 200)
|
|
97
|
+
throw new BravosError(`${device.origin} answered HTTP ${status}; nothing was revoked`);
|
|
98
|
+
return [`Revoked ${deviceId}: that machine's licence stops working at its next check with the portal.`];
|
|
99
|
+
}
|
|
100
|
+
// @comment -- "bravos account logout: revokes this machine at the portal (POST /api/v1/cli/devices/revoke, no body = this device), then removes licence.jwt and device.json — always, even when the portal cannot be reached, and the output says which of the two happened. A machine without a device record only has its local licence file removed."
|
|
101
|
+
export async function logout(io) {
|
|
102
|
+
const R = await refreshLib();
|
|
103
|
+
const device = R.readDevice(io.env);
|
|
104
|
+
const lines = [];
|
|
105
|
+
if (device) {
|
|
106
|
+
try {
|
|
107
|
+
const { status } = await call(io, device, R.REVOKE_PATH, { method: 'POST' });
|
|
108
|
+
if (status === 200 || status === 401 || status === 403 || status === 404)
|
|
109
|
+
lines.push(`Signed this machine out of ${device.origin}; its licence no longer works there.`);
|
|
110
|
+
else
|
|
111
|
+
lines.push(`${device.origin} answered HTTP ${status}, so the portal may still list this machine — remove it at ${device.origin}/dashboard/license.`);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
lines.push(`Could not reach ${device.origin}, so the portal still lists this machine — remove it at ${device.origin}/dashboard/license. The local licence is removed anyway.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
else
|
|
118
|
+
lines.push('This machine has no device record; only the local licence file is removed.');
|
|
119
|
+
const removed = R.forgetDevice(io.env);
|
|
120
|
+
lines.push(removed.length ? `Removed ${removed.join(' and ')}. This machine is on Free.` : 'No local licence to remove. This machine is on Free.');
|
|
121
|
+
if (io.env.BRAVOS_LICENCE || io.env.BRAVOS_LICENSE)
|
|
122
|
+
lines.push('BRAVOS_LICENCE is still set in this environment and still applies; unset it to stop using it.');
|
|
123
|
+
return lines;
|
|
124
|
+
}
|
package/dist/guide.js
CHANGED
|
@@ -25,7 +25,7 @@ export const GUIDE_TOPICS = [
|
|
|
25
25
|
{
|
|
26
26
|
name: 'Plans',
|
|
27
27
|
body: [
|
|
28
|
-
'Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in one repository. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.',
|
|
28
|
+
'Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in one repository. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. On a team plan the licence is yours and this machine\'s: an owner or admin assigns you a licence, each machine you activate gets its own short-lived token that bravos renews automatically (at the session start and before a paid command), bravos account devices lists your machines, bravos account revoke <id> signs one out (a lost laptop), and bravos account logout signs this one out. Removing you from the team, or taking your licence back, stops every one of your machines at its next renewal. In CI, BRAVOS_LICENCE holds a CI licence an owner or admin creates for that repository, and the CLI never renews it. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.',
|
|
29
29
|
],
|
|
30
30
|
},
|
|
31
31
|
{
|
package/dist/help.js
CHANGED
|
@@ -53,10 +53,13 @@ Commands
|
|
|
53
53
|
graph --json lists every question this machine's binary answers.
|
|
54
54
|
licence Which plan this machine is on, where the licence is, what it unlocks
|
|
55
55
|
(--json: bravos.licence/v1). 'license' works too.
|
|
56
|
-
account <activate|import FILE|status>
|
|
56
|
+
account <activate|import FILE|status|refresh|devices|revoke ID|logout>
|
|
57
57
|
activate: sign in once in the browser and get this machine its licence — a
|
|
58
|
-
30-day Team trial when the account has no plan, no card
|
|
59
|
-
licence
|
|
58
|
+
30-day Team trial when the account has no plan, no card; on a team plan the
|
|
59
|
+
licence is yours, for this machine, and renews itself. import: install a
|
|
60
|
+
licence downloaded from account.bugb.io/dashboard/license. refresh: renew
|
|
61
|
+
now. devices: your signed-in machines. revoke ID: sign one out. logout: sign
|
|
62
|
+
this machine out and remove its licence.
|
|
60
63
|
guide [topic] How to use bravos: by role, by task, every skill, the safety rules.
|
|
61
64
|
Topics: start, roles, tasks, skills, states, safety, harnesses, all.
|
|
62
65
|
Run 'bravos <command> --help' for every flag and what it writes.
|
|
@@ -68,8 +71,9 @@ Plans
|
|
|
68
71
|
workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph.
|
|
69
72
|
A paid command or flag without a licence says what it would do and how to start the trial;
|
|
70
73
|
a paid hook stands down with one line and never blocks. The licence is an offline-verified
|
|
71
|
-
token: BRAVOS_LICENCE,
|
|
72
|
-
|
|
74
|
+
token: BRAVOS_LICENCE (in CI, a CI licence from the account portal), or licence.jwt in
|
|
75
|
+
$BRAVOS_HOME (default ~/.bravos), renewed automatically for a signed-in machine. Grace after
|
|
76
|
+
expiry is min(14 days, a quarter of the term). Seats are licences an owner or admin assigns.
|
|
73
77
|
|
|
74
78
|
The skills it installs (one folder each in .claude/skills/ and .agents/skills/)
|
|
75
79
|
bravos Start here: reads the briefing, explains the loop, routes to the rest.
|
package/dist/licence.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// @comment -- "The CLI's view of the licence: a typed wrapper over hooks/lib/licence.mjs (the one implementation, shared with the session hooks), plus the gate every paid command calls. Nothing here verifies on its own; it asks the library and turns a refusal into a BravosError the person can act on."
|
|
2
2
|
import { pathToFileURL } from 'node:url';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
+
import { refresh } from './device.js';
|
|
4
5
|
import { hooksDir } from './paths.js';
|
|
5
6
|
import { BravosError } from './types.js';
|
|
6
7
|
let cached = null;
|
|
@@ -8,13 +9,15 @@ export const licenceLib = () => (cached ??= import(pathToFileURL(join(hooksDir()
|
|
|
8
9
|
export async function licenceStatus(env) {
|
|
9
10
|
return (await licenceLib()).status(env);
|
|
10
11
|
}
|
|
11
|
-
// @comment -- "The gate: returns the status when `feature` is unlocked, else throws a BravosError whose message says what `what` does, that it is on the Team plan, and how to start the trial or renew. Every paid command and flag goes through here, so a refusal always reads the same."
|
|
12
|
-
export async function requireFeature(env, feature, what) {
|
|
12
|
+
// @comment -- "The gate: first renews this machine's device licence when it is due (hooks/lib/refresh.mjs; fail-open, never for a token from the environment), then returns the status when `feature` is unlocked, else throws a BravosError whose message says what `what` does, that it is on the Team plan, and how to start the trial or renew — prefixed with why, when the renewal found this machine is no longer licensed. Every paid command and flag goes through here, so a refusal always reads the same."
|
|
13
|
+
export async function requireFeature(env, feature, what, io = {}) {
|
|
13
14
|
const L = await licenceLib();
|
|
15
|
+
const renewed = await refresh({ env, fetch: io.fetch });
|
|
14
16
|
const v = L.status(env);
|
|
15
17
|
if (L.entitled(v, feature))
|
|
16
18
|
return v;
|
|
17
|
-
|
|
19
|
+
const why = renewed.outcome === 'revoked' || renewed.outcome === 'lapsed' ? `${renewed.note} ` : '';
|
|
20
|
+
throw new BravosError(why + L.refusal(v, feature, what));
|
|
18
21
|
}
|
|
19
22
|
/** The JSON document `bravos licence --json` prints: the status without the tenant id (an account id is not for logs). */
|
|
20
23
|
export function licenceDocument(v) {
|
package/dist/plugin-release.js
CHANGED
|
@@ -16,16 +16,19 @@ const KEYWORDS = ['security', 'threat-modeling', 'guardlink', 'pentest', 'cxg',
|
|
|
16
16
|
const SESSION_MATCHER = 'startup|resume|clear|compact';
|
|
17
17
|
const json = (v) => Buffer.from(JSON.stringify(v, null, 2) + '\n');
|
|
18
18
|
const text = (s) => Buffer.from(s.endsWith('\n') ? s : s + '\n');
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
if (
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
19
|
+
// @comment -- "The hook files a plugin ships: the session-start script and every file it imports, followed through relative imports. Plugins register only SessionStart; the pre-PR gate and autopilot run through the installed CLI (bravos hook), so their scripts are not shipped where a reviewer would have to read them."
|
|
20
|
+
export function hookClosure(hooks, entry = 'session-start.mjs') {
|
|
21
|
+
const seen = new Set();
|
|
22
|
+
const visit = (abs) => {
|
|
23
|
+
if (seen.has(abs))
|
|
24
|
+
return;
|
|
25
|
+
seen.add(abs);
|
|
26
|
+
const src = readFileSync(abs, 'utf8');
|
|
27
|
+
for (const m of src.matchAll(/(?:from\s+|import\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g))
|
|
28
|
+
visit(join(dirname(abs), m[1]));
|
|
29
|
+
};
|
|
30
|
+
visit(join(hooks, entry));
|
|
31
|
+
return [...seen].sort();
|
|
29
32
|
}
|
|
30
33
|
const guardlinkServer = () => ({ type: 'stdio', command: SERVERS.guardlink.command, args: [...SERVERS.guardlink.args] });
|
|
31
34
|
// @comment -- "Every file of the public plugin repository, computed and not written. Skills: Claude Code's copy uses ${CLAUDE_SKILL_DIR} and ${CLAUDE_PLUGIN_ROOT}, which it substitutes; every other copy uses the portable SKILL_DIR wording. In every copy a skill's `node .bravos/hooks/<hook>.mjs` is `bravos hook <hook>`, because a plugin install has no .bravos/hooks/. Session hooks are registered where the harness's plugin format and SessionStart output are known: Claude Code, Codex, Gemini CLI and Antigravity. Copilot, VS Code and Cursor get the skills and MCP, and the bravos skill loads the briefing itself."
|
|
@@ -35,7 +38,7 @@ export function releaseFiles(opts = {}) {
|
|
|
35
38
|
const add = (path, content) => files.push({ path, content });
|
|
36
39
|
const skills = listBundledSkills(opts.skillsDir);
|
|
37
40
|
const hooks = opts.hooksDir ?? hooksDir();
|
|
38
|
-
const hookFiles =
|
|
41
|
+
const hookFiles = hookClosure(hooks);
|
|
39
42
|
const licence = opts.licence ?? readFileSync(join(packageRoot(), 'LICENSE'));
|
|
40
43
|
const addSkills = (prefix, render) => {
|
|
41
44
|
for (const skill of skills) {
|
|
@@ -50,14 +53,27 @@ export function releaseFiles(opts = {}) {
|
|
|
50
53
|
add(`${prefix}hooks/${relative(hooks, abs).split('\\').join('/')}`, readFileSync(abs));
|
|
51
54
|
};
|
|
52
55
|
const sessionGroup = (command) => ({ matcher: SESSION_MATCHER, hooks: [{ type: 'command', command, timeout: 30 }] });
|
|
56
|
+
// Claude's directory wants the interpreter in command and the file first in args, which also starts on Windows without a shell.
|
|
57
|
+
const sessionArgs = (file, harness) => ({ matcher: SESSION_MATCHER, hooks: [{ type: 'command', command: 'node', args: [file, '--harness', harness], timeout: 30 }] });
|
|
58
|
+
const icon = opts.icon ?? readFileSync(join(packageRoot(), 'assets', 'plugin-icon.png'));
|
|
53
59
|
const base = { name: NAME, version: v, description: DESCRIPTION, author: AUTHOR, homepage: HOMEPAGE, repository: REPOSITORY, license: LICENSE_ID, keywords: KEYWORDS };
|
|
54
60
|
// Claude Code: claude/, listed by .claude-plugin/marketplace.json.
|
|
55
61
|
addSkills('claude/', (c, rel) => viaCliHooks(renderPluginSkillFile(c, rel)));
|
|
56
62
|
addHookScripts('claude/');
|
|
57
|
-
add('claude/hooks/hooks.json', json({ hooks: { SessionStart: [
|
|
63
|
+
add('claude/hooks/hooks.json', json({ hooks: { SessionStart: [sessionArgs('${CLAUDE_PLUGIN_ROOT}/hooks/session-start.mjs', 'claude')] } }));
|
|
64
|
+
add('claude/.claude-plugin/icon.png', icon);
|
|
58
65
|
add('claude/.mcp.json', json({ mcpServers: { guardlink: SERVERS.guardlink } }));
|
|
59
|
-
|
|
66
|
+
// Claude's directory shows these links on the listing; the pages are the company site's own.
|
|
67
|
+
add('claude/.claude-plugin/plugin.json', json({
|
|
68
|
+
...base,
|
|
69
|
+
displayName: 'Bravos',
|
|
70
|
+
documentationUrl: HOMEPAGE,
|
|
71
|
+
supportUrl: 'https://www.bugb.io/contact',
|
|
72
|
+
privacyPolicyUrl: 'https://www.bugb.io/privacy',
|
|
73
|
+
termsOfServiceUrl: 'https://www.bugb.io/terms',
|
|
74
|
+
}));
|
|
60
75
|
add('claude/LICENSE', licence);
|
|
76
|
+
add('claude/README.md', text(readme(v)));
|
|
61
77
|
add('.claude-plugin/marketplace.json', json({
|
|
62
78
|
name: NAME,
|
|
63
79
|
owner: AUTHOR,
|
|
@@ -82,8 +98,11 @@ export function releaseFiles(opts = {}) {
|
|
|
82
98
|
capabilities: ['Read', 'Write'],
|
|
83
99
|
websiteURL: HOMEPAGE,
|
|
84
100
|
defaultPrompt: ['Where do I start on security here?', 'Threat-model this repository', 'Is this PR safe to open?'],
|
|
101
|
+
composerIcon: './assets/icon.png',
|
|
102
|
+
logo: './assets/icon.png',
|
|
85
103
|
},
|
|
86
104
|
}));
|
|
105
|
+
add('codex/assets/icon.png', icon);
|
|
87
106
|
add('codex/LICENSE', licence);
|
|
88
107
|
add('.agents/plugins/marketplace.json', json({
|
|
89
108
|
name: NAME,
|
|
@@ -128,12 +147,14 @@ export function releaseFiles(opts = {}) {
|
|
|
128
147
|
add('.antigravity-plugin/plugin.json', json({
|
|
129
148
|
...base,
|
|
130
149
|
displayName: 'Bravos',
|
|
150
|
+
logo: 'assets/icon.png',
|
|
131
151
|
suggestedPrompts: ['Where do I start on security here?', 'Threat-model this repository', 'Is this PR safe to open?'],
|
|
132
152
|
}));
|
|
133
153
|
add('hooks.json', json({ bravos: { SessionStart: [{ type: 'command', command: 'node hooks/session-start.mjs --harness agy', timeout: 30 }] } }));
|
|
134
154
|
// Antigravity loads a plugin's context only from rules/; GEMINI.md is Gemini CLI's.
|
|
135
155
|
add('rules/bravos.md', text(GEMINI_CONTEXT));
|
|
136
156
|
add('mcp_config.json', json({ mcpServers: { guardlink: { command: SERVERS.guardlink.command, args: [...SERVERS.guardlink.args] } } }));
|
|
157
|
+
add('assets/icon.png', icon);
|
|
137
158
|
add('LICENSE', licence);
|
|
138
159
|
add('README.md', text(readme(v)));
|
|
139
160
|
return files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
@@ -177,6 +198,28 @@ Then install the plugin for your agent:
|
|
|
177
198
|
You do not need a plugin: \`bravos init\` in a repository installs the same skills,
|
|
178
199
|
hooks and MCP wiring for every agent it finds, and commits them with the code.
|
|
179
200
|
|
|
201
|
+
## Where data goes
|
|
202
|
+
|
|
203
|
+
Bravos runs on your machine, and the plugin sends nothing to Bugb. Its skills
|
|
204
|
+
and the CLI they call reach only these places, each one started by you or by a
|
|
205
|
+
skill you run:
|
|
206
|
+
|
|
207
|
+
- **account.bugb.io:** \`bravos account activate\` (signing in once in the browser
|
|
208
|
+
to get a licence) and \`bravos setup\` (downloading the SAST analyzer and the code
|
|
209
|
+
graph with your licence). Your licence goes there; your code does not.
|
|
210
|
+
- **GitHub:** the session briefing uses \`gh\`, if it is installed and signed in, to
|
|
211
|
+
list open pull requests in your repository. The CI workflows \`bravos sync --ci\`
|
|
212
|
+
writes run on GitHub Actions in your own repository.
|
|
213
|
+
- **A test target you own:** \`bravos-prove\` and \`bravos-recheck\` send test
|
|
214
|
+
requests through cxg. Loopback by default; any other host only with a reviewed
|
|
215
|
+
\`.guardlink/scope.yaml\` and your own typed authorization naming it.
|
|
216
|
+
- **A model API, only if you agree:** cxg can generate probes through a model API
|
|
217
|
+
you configure. The skill asks before it spends.
|
|
218
|
+
- **npm and crates.io:** \`bravos setup --tools\` installs guardlink and cxg.
|
|
219
|
+
|
|
220
|
+
The threat model, test results and reports stay in your repository. Bugb keeps
|
|
221
|
+
nothing from your sessions.
|
|
222
|
+
|
|
180
223
|
## Plans
|
|
181
224
|
|
|
182
225
|
The research loop is free for one researcher in one repository. The pre-PR gate
|
package/dist/setup.js
CHANGED
|
@@ -37,7 +37,7 @@ export async function runSetup(env, opts, io) {
|
|
|
37
37
|
const bundles = [...(pick.codegraph ? ['codegraph'] : []), ...(pick.analyzer ? ['analyzer'] : [])];
|
|
38
38
|
for (const kind of bundles) {
|
|
39
39
|
const what = `bravos setup --${kind}`;
|
|
40
|
-
await requireFeature(env, kind === 'analyzer' ? 'sast' : 'codegraph', what);
|
|
40
|
+
await requireFeature(env, kind === 'analyzer' ? 'sast' : 'codegraph', what, { fetch: io.fetch });
|
|
41
41
|
const have = staged(env, kind);
|
|
42
42
|
if (have && !opts.yes) {
|
|
43
43
|
lines.push(`${kind}: already staged at ${have} (add -y to fetch ${VERSIONS[kind]} again)`);
|
package/docs/GUIDE.md
CHANGED
|
@@ -22,7 +22,7 @@ Claude Code and opencode: /bravos-ship. Codex: $bravos-ship. omp: /skill:bravos-
|
|
|
22
22
|
|
|
23
23
|
### Plans
|
|
24
24
|
|
|
25
|
-
Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in one repository. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.
|
|
25
|
+
Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in one repository. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. On a team plan the licence is yours and this machine's: an owner or admin assigns you a licence, each machine you activate gets its own short-lived token that bravos renews automatically (at the session start and before a paid command), bravos account devices lists your machines, bravos account revoke <id> signs one out (a lost laptop), and bravos account logout signs this one out. Removing you from the team, or taking your licence back, stops every one of your machines at its next renewal. In CI, BRAVOS_LICENCE holds a CI licence an owner or admin creates for that repository, and the CLI never renews it. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.
|
|
26
26
|
|
|
27
27
|
### Effort
|
|
28
28
|
|
package/hooks/lib/autopilot.mjs
CHANGED
|
@@ -53,28 +53,9 @@ async function json(run, args, o) {
|
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
// @comment -- "
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
try {
|
|
60
|
-
text = readFileSync(join(root, '.guardlink', 'proving.md'), 'utf8');
|
|
61
|
-
} catch {
|
|
62
|
-
return { status: 'not set' };
|
|
63
|
-
}
|
|
64
|
-
const field = (name) => text.match(new RegExp(`^${name}:\\s*(\\S[^\\n]*?)\\s*$`, 'mi'))?.[1]?.replace(/\s+\(.*\)$/, '') ?? null;
|
|
65
|
-
const by = text.match(/—\s*confirmed by\s+([^,\n]+?)\s*,\s*(\S+)/i);
|
|
66
|
-
const choice = (field('choice') ?? '').toLowerCase().split(/\s/)[0];
|
|
67
|
-
if (!by || !['auto', 'ask', 'schedule', 'none'].includes(choice)) return { status: 'not set' };
|
|
68
|
-
return {
|
|
69
|
-
status: 'set',
|
|
70
|
-
choice,
|
|
71
|
-
target: field('target'),
|
|
72
|
-
start: field('start'),
|
|
73
|
-
generation: /^(yes|true|allowed)/i.test(field('generation') ?? ''),
|
|
74
|
-
by: by[1],
|
|
75
|
-
date: by[2],
|
|
76
|
-
};
|
|
77
|
-
}
|
|
56
|
+
// @comment -- "readProving lives in proving.mjs, a file with no process or environment access, so the session-start hook can import it without this module; re-exported here for existing callers."
|
|
57
|
+
import { readProving } from './proving.mjs';
|
|
58
|
+
export { readProving };
|
|
78
59
|
|
|
79
60
|
/** Files changed in the working tree since HEAD, tracked or not. */
|
|
80
61
|
export async function changedFiles(root, env, run) {
|
package/hooks/lib/briefing.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
// @comment -- "Pure text builder for the session-start briefing, collect() which gathers its read-only guardlink, git and gh facts concurrently under a shared deadline, and the runJson/runJsonAsync spawn wrappers; dependency-free so it can be copied verbatim into target repos."
|
|
1
|
+
// @comment -- "Pure text builder for the session-start briefing, collect() which gathers its read-only guardlink, git and gh facts concurrently under a shared deadline (and renews a signed-in machine's device licence when it is due, through refresh.mjs — the one write it makes, to $BRAVOS_HOME only), and the runJson/runJsonAsync spawn wrappers; dependency-free so it can be copied verbatim into target repos."
|
|
2
2
|
import { spawn, spawnSync } from 'node:child_process';
|
|
3
3
|
import { accessSync, constants, readFileSync } from 'node:fs';
|
|
4
4
|
import { basename, delimiter, dirname, join } from 'node:path';
|
|
5
|
-
import { readProving } from './
|
|
5
|
+
import { readProving } from './proving.mjs';
|
|
6
6
|
import { planLine, status as licenceStatus } from './licence.mjs';
|
|
7
|
+
import { refreshIfDue } from './refresh.mjs';
|
|
7
8
|
import { readSast, sastAvailable, sastLine } from './sast.mjs';
|
|
8
9
|
import { readSetup, setupLine } from './setup.mjs';
|
|
9
10
|
import { memberCounts, readWorkspace, workspaceLines } from './workspace.mjs';
|
|
@@ -340,10 +341,12 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
340
341
|
});
|
|
341
342
|
|
|
342
343
|
const graphRun = probeGraph(root, env, Math.min(3000, first));
|
|
344
|
+
// A signed-in machine's device licence is renewed here when it is due, alongside the other facts and under a short timeout of its own; it fails open, so a slow or absent portal only means the held token is read as it is.
|
|
345
|
+
const renewal = refreshIfDue(env, { timeoutMs: Math.min(3000, first) }).catch(() => null);
|
|
343
346
|
// At an app folder, each member's counts come from its own guardlink ci, alongside the rest.
|
|
344
347
|
const workspace = readWorkspace(root);
|
|
345
348
|
const countsRun = workspace?.isAppFolder && hasGuardlink ? memberCounts(workspace, runJsonAsync, env, first) : Promise.resolve(null);
|
|
346
|
-
const [facts, pr, graphState, workspaceCounts, ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, ...glRuns]);
|
|
349
|
+
const [facts, pr, graphState, workspaceCounts, , ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, renewal, ...glRuns]);
|
|
347
350
|
|
|
348
351
|
let guardlink = 'missing';
|
|
349
352
|
if (hasGuardlink) {
|
package/hooks/lib/pre-pr.mjs
CHANGED
|
@@ -8,7 +8,7 @@ const READY_ARG = /(?:^|[\s;&|(])gh\s+pr\s+ready\s+([^\s;&|)-][^\s;&|)]*)/;
|
|
|
8
8
|
const BODY_FILE = /(?:--body-file|-F)[=\s]+("([^"]+)"|'([^']+)'|(\S+))/;
|
|
9
9
|
// @comment -- "The hook is registered with a 180 s timeout; the whole gate shares 150 s so it always answers before the harness kills it."
|
|
10
10
|
export const GATE_DEADLINE_MS = 150000;
|
|
11
|
-
// @comment -- "The person's recorded proving preference (see
|
|
11
|
+
// @comment -- "The person's recorded proving preference (see proving.mjs readProving); a branch that changes it must disclose that in the PR body."
|
|
12
12
|
export const PROVING_FILE = '.guardlink/proving.md';
|
|
13
13
|
const SPAWN_CAP_MS = 60000;
|
|
14
14
|
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
// @comment -- "Reads .guardlink/proving.md, the person's recorded answer to how findings should be proven (written by the agent from their words in bravos-env/bravos-prove): choice auto | ask | schedule | none, the loopback target, the start command, whether model-API generation is allowed, and who confirmed it. Anything without a named confirmation reads as not set."
|
|
5
|
+
export function readProving(root) {
|
|
6
|
+
let text;
|
|
7
|
+
try {
|
|
8
|
+
text = readFileSync(join(root, '.guardlink', 'proving.md'), 'utf8');
|
|
9
|
+
} catch {
|
|
10
|
+
return { status: 'not set' };
|
|
11
|
+
}
|
|
12
|
+
const field = (name) => text.match(new RegExp(`^${name}:\\s*(\\S[^\\n]*?)\\s*$`, 'mi'))?.[1]?.replace(/\s+\(.*\)$/, '') ?? null;
|
|
13
|
+
const by = text.match(/—\s*confirmed by\s+([^,\n]+?)\s*,\s*(\S+)/i);
|
|
14
|
+
const choice = (field('choice') ?? '').toLowerCase().split(/\s/)[0];
|
|
15
|
+
if (!by || !['auto', 'ask', 'schedule', 'none'].includes(choice)) return { status: 'not set' };
|
|
16
|
+
return {
|
|
17
|
+
status: 'set',
|
|
18
|
+
choice,
|
|
19
|
+
target: field('target'),
|
|
20
|
+
start: field('start'),
|
|
21
|
+
generation: /^(yes|true|allowed)/i.test(field('generation') ?? ''),
|
|
22
|
+
by: by[1],
|
|
23
|
+
date: by[2],
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// @comment -- "Keeps a per-machine (device) licence current: the account portal issues each `bravos account activate` a short-lived token for (account, person, machine) carrying non-critical `uid`/`did` claims, and the device code from that pairing becomes this machine's refresh secret, kept in $BRAVOS_HOME/device.json (0600). refreshIfDue() trades the secret for a fresh token at the portal origin recorded at activation, once less than half the token's term is left (or it has expired, or the file is missing), verifies the new token with the same offline verifier before writing it, and fails OPEN on a network error, a timeout or a 5xx — the held token keeps working for whatever term it has. A refusal that means the machine is no longer licensed (401 invalid_device; 403 device_revoked, licence_unassigned, account_unavailable) removes the token and the device file, so the machine is back on Free and says why. A token supplied through BRAVOS_LICENCE / BRAVOS_LICENSE (CI) is never refreshed. Dependency-free (node:fs and the global fetch) so the session hook and the CLI share this one implementation."
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { ACCOUNT_LICENCES, ACCOUNT_UPGRADE, LICENCE_ENV, LICENCE_ENV_ALT, LICENCE_FILES, bravosHome, verify } from './licence.mjs';
|
|
5
|
+
|
|
6
|
+
export const DEVICE_FILE = 'device.json';
|
|
7
|
+
export const REFRESH_PATH = '/api/v1/cli/licence/refresh';
|
|
8
|
+
export const DEVICES_PATH = '/api/v1/cli/devices';
|
|
9
|
+
export const REVOKE_PATH = '/api/v1/cli/devices/revoke';
|
|
10
|
+
export const REFRESH_TIMEOUT_MS = 5000;
|
|
11
|
+
/** After a refresh that could not reach the portal, an unforced refresh waits this long before trying again. */
|
|
12
|
+
export const RETRY_AFTER_FAILURE_SECONDS = 15 * 60;
|
|
13
|
+
/** The portal's device code is 32 random bytes, base64url (43 characters); anything else never goes in a header. */
|
|
14
|
+
const SECRET_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
15
|
+
const ORIGIN_RE = /^https?:\/\/[^/\s]+$/;
|
|
16
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
17
|
+
/** The refusals that mean this machine is no longer licensed; anything else is a reason to keep the token. */
|
|
18
|
+
export const REVOKED_ERRORS = ['invalid_device', 'device_revoked', 'licence_unassigned', 'account_unavailable'];
|
|
19
|
+
|
|
20
|
+
export const isDeviceSecret = (s) => typeof s === 'string' && SECRET_RE.test(s);
|
|
21
|
+
export const isDeviceId = (s) => typeof s === 'string' && UUID_RE.test(s);
|
|
22
|
+
|
|
23
|
+
/** The licence file activate and refresh write: $BRAVOS_HOME/licence.jwt. */
|
|
24
|
+
export const licencePath = (env = process.env) => {
|
|
25
|
+
const home = bravosHome(env);
|
|
26
|
+
return home ? join(home, LICENCE_FILES[0]) : null;
|
|
27
|
+
};
|
|
28
|
+
export const devicePath = (env = process.env) => {
|
|
29
|
+
const home = bravosHome(env);
|
|
30
|
+
return home ? join(home, DEVICE_FILE) : null;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// @comment -- "Reads $BRAVOS_HOME/device.json and accepts it only when every field has the shape the portal issues (an http(s) origin, a 43-character base64url secret, a uuid device id or none), so a hand-edited or truncated file can never put arbitrary text into a request header or send the secret to a different kind of URL."
|
|
34
|
+
export function readDevice(env = process.env) {
|
|
35
|
+
const file = devicePath(env);
|
|
36
|
+
if (!file) return null;
|
|
37
|
+
let raw;
|
|
38
|
+
try {
|
|
39
|
+
raw = JSON.parse(readFileSync(file, 'utf8'));
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
44
|
+
if (typeof raw.origin !== 'string' || !ORIGIN_RE.test(raw.origin)) return null;
|
|
45
|
+
if (!isDeviceSecret(raw.device_secret)) return null;
|
|
46
|
+
const deviceId = isDeviceId(raw.device_id) ? raw.device_id : null;
|
|
47
|
+
const failedAt = typeof raw.refresh_failed_at === 'number' && Number.isFinite(raw.refresh_failed_at) ? raw.refresh_failed_at : null;
|
|
48
|
+
return { origin: raw.origin, device_id: deviceId, device_secret: raw.device_secret, refresh_failed_at: failedAt };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Writes a file 0600 in a 0700 folder, through a temporary sibling and a rename so a reader never sees half of it. */
|
|
52
|
+
function writePrivate(file, text) {
|
|
53
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
54
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
55
|
+
writeFileSync(tmp, text, { mode: 0o600 });
|
|
56
|
+
try {
|
|
57
|
+
chmodSync(tmp, 0o600);
|
|
58
|
+
} catch {
|
|
59
|
+
/* best effort on platforms without modes */
|
|
60
|
+
}
|
|
61
|
+
renameSync(tmp, file);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// @comment -- "Writes device.json (0600, folder 0700): the portal origin, the device id and the refresh secret. Refuses a record that would not read back, so a bad value is caught at activation rather than at the first refresh."
|
|
65
|
+
export function writeDevice(env, record) {
|
|
66
|
+
const file = devicePath(env);
|
|
67
|
+
if (!file) throw new Error('no home directory: set BRAVOS_HOME');
|
|
68
|
+
if (!ORIGIN_RE.test(record.origin ?? '') || !isDeviceSecret(record.device_secret)) throw new Error('refusing to write a device record the portal did not issue');
|
|
69
|
+
const out = { origin: record.origin, device_id: isDeviceId(record.device_id) ? record.device_id : null, device_secret: record.device_secret };
|
|
70
|
+
if (typeof record.refresh_failed_at === 'number') out.refresh_failed_at = record.refresh_failed_at;
|
|
71
|
+
writePrivate(file, JSON.stringify(out, null, 2) + '\n');
|
|
72
|
+
return file;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Writes the licence token to $BRAVOS_HOME/licence.jwt, 0600. */
|
|
76
|
+
export function writeLicence(env, token) {
|
|
77
|
+
const file = licencePath(env);
|
|
78
|
+
if (!file) throw new Error('no home directory: set BRAVOS_HOME');
|
|
79
|
+
writePrivate(file, token.trim() + '\n');
|
|
80
|
+
return file;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// @comment -- "Removes this machine's licence and device record (licence.jwt and device.json under $BRAVOS_HOME), the local half of a logout or a revocation. Only those two files: a licence kept elsewhere, or in the environment, is the person's own and is left alone."
|
|
84
|
+
export function forgetDevice(env = process.env) {
|
|
85
|
+
const removed = [];
|
|
86
|
+
for (const file of [licencePath(env), devicePath(env)]) {
|
|
87
|
+
if (!file) continue;
|
|
88
|
+
try {
|
|
89
|
+
rmSync(file);
|
|
90
|
+
removed.push(file);
|
|
91
|
+
} catch {
|
|
92
|
+
/* already gone */
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return removed;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The claims of a token, unverified — read only after verify() has accepted it, for `did`, `iat` and `exp`. */
|
|
99
|
+
export function claimsOf(token) {
|
|
100
|
+
try {
|
|
101
|
+
const parsed = JSON.parse(Buffer.from(String(token).split('.')[1] ?? '', 'base64url').toString('utf8'));
|
|
102
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** True when a verified device token should be replaced: past half its term, expired, in grace, or unreadable. */
|
|
109
|
+
export function refreshDue(v, now) {
|
|
110
|
+
if (v.state !== 'valid') return true;
|
|
111
|
+
if (typeof v.expiresAt !== 'number' || typeof v.issuedAt !== 'number') return true;
|
|
112
|
+
const term = v.expiresAt - v.issuedAt;
|
|
113
|
+
if (!(term > 0)) return true;
|
|
114
|
+
return v.expiresAt - now < term / 2;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const readToken = (file) => {
|
|
118
|
+
try {
|
|
119
|
+
return readFileSync(file, 'utf8').trim() || null;
|
|
120
|
+
} catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** What to tell the person when the portal says this machine is no longer licensed. */
|
|
126
|
+
export function revokedNote(error) {
|
|
127
|
+
if (error === 'licence_unassigned') return `You no longer hold a licence on your team's account, so this machine is back on Free. Ask an owner or admin for a licence (${ACCOUNT_LICENCES}), then run bravos account activate.`;
|
|
128
|
+
if (error === 'device_revoked') return 'This machine was removed from your account in the account portal, so it is back on Free. To use the Team features here again, run bravos account activate.';
|
|
129
|
+
if (error === 'account_unavailable') return "Your team's account is not available, so this machine is back on Free. Ask your account owner, or contact Bugb support.";
|
|
130
|
+
return 'The account portal no longer recognises this machine, so it is back on Free. Run bravos account activate to sign it in again.';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const sameOriginLink = (link, origin, fallback) => (typeof link === 'string' && link.startsWith(origin + '/') ? link : fallback);
|
|
134
|
+
|
|
135
|
+
// @comment -- "The refresh itself: POST <origin>/api/v1/cli/licence/refresh with the device secret as a bearer, to the origin stored at activation and nowhere else, under a timeout. Outcomes: skipped (no device file, an environment token, BRAVOS_NO_FETCH or BRAVOS_REFRESH=off, or not a device token), fresh (not due), refreshed (a new token verified and written), kept (fail-open: no answer, a 5xx, a 429, or an answer that did not verify — the held token stays), lapsed (402: the plan ended; the token runs out on its own), revoked (the licence and device file are removed). Never throws."
|
|
136
|
+
export async function refreshIfDue(env = process.env, opts = {}) {
|
|
137
|
+
const now = opts.now ?? Math.floor(Date.now() / 1000);
|
|
138
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
139
|
+
const force = !!opts.force;
|
|
140
|
+
try {
|
|
141
|
+
if ((env[LICENCE_ENV] || '').trim() || (env[LICENCE_ENV_ALT] || '').trim()) return { outcome: 'skipped', reason: 'environment' };
|
|
142
|
+
if (env.BRAVOS_NO_FETCH || env.BRAVOS_REFRESH === 'off') return { outcome: 'skipped', reason: 'disabled' };
|
|
143
|
+
const device = readDevice(env);
|
|
144
|
+
if (!device) return { outcome: 'skipped', reason: 'no-device' };
|
|
145
|
+
const file = licencePath(env);
|
|
146
|
+
const token = file ? readToken(file) : null;
|
|
147
|
+
if (token) {
|
|
148
|
+
const v = verify(token);
|
|
149
|
+
const claims = v.state === 'invalid' ? null : claimsOf(token);
|
|
150
|
+
// A licence that is not a device token (an import, a trial) is not this refresh's to replace.
|
|
151
|
+
if (claims && typeof claims.did !== 'string') return { outcome: 'skipped', reason: 'not-a-device-token' };
|
|
152
|
+
if (!force && v.state !== 'invalid' && !refreshDue(v, now)) return { outcome: 'fresh' };
|
|
153
|
+
}
|
|
154
|
+
if (!force && device.refresh_failed_at !== null && now - device.refresh_failed_at < RETRY_AFTER_FAILURE_SECONDS) return { outcome: 'kept', reason: 'backing-off' };
|
|
155
|
+
|
|
156
|
+
const keep = (reason) => {
|
|
157
|
+
try {
|
|
158
|
+
writeDevice(env, { ...device, refresh_failed_at: now });
|
|
159
|
+
} catch {
|
|
160
|
+
/* the backoff marker is a courtesy */
|
|
161
|
+
}
|
|
162
|
+
return { outcome: 'kept', reason };
|
|
163
|
+
};
|
|
164
|
+
let r;
|
|
165
|
+
try {
|
|
166
|
+
r = await f(`${device.origin}${REFRESH_PATH}`, {
|
|
167
|
+
method: 'POST',
|
|
168
|
+
headers: { 'User-Agent': opts.userAgent ?? 'bravos-cli', Accept: 'application/json', Authorization: `Bearer ${device.device_secret}` },
|
|
169
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? REFRESH_TIMEOUT_MS),
|
|
170
|
+
});
|
|
171
|
+
} catch {
|
|
172
|
+
return keep('unreachable');
|
|
173
|
+
}
|
|
174
|
+
let body = null;
|
|
175
|
+
try {
|
|
176
|
+
body = await r.json();
|
|
177
|
+
} catch {
|
|
178
|
+
body = null;
|
|
179
|
+
}
|
|
180
|
+
const error = body && typeof body.error === 'string' ? body.error : null;
|
|
181
|
+
if (r.status === 200) {
|
|
182
|
+
const fresh = body && typeof body.license === 'string' ? body.license.trim() : '';
|
|
183
|
+
const nv = fresh ? verify(fresh) : null;
|
|
184
|
+
if (!nv || nv.state === 'invalid') return keep('unverified');
|
|
185
|
+
writeLicence(env, fresh);
|
|
186
|
+
const did = claimsOf(fresh)?.did;
|
|
187
|
+
writeDevice(env, { origin: device.origin, device_id: isDeviceId(did) ? did : device.device_id, device_secret: device.device_secret });
|
|
188
|
+
return { outcome: 'refreshed', expiresAt: nv.expiresAt };
|
|
189
|
+
}
|
|
190
|
+
if (r.status === 401 || (r.status === 403 && REVOKED_ERRORS.includes(error))) {
|
|
191
|
+
const why = r.status === 401 ? 'invalid_device' : error;
|
|
192
|
+
forgetDevice(env);
|
|
193
|
+
return { outcome: 'revoked', reason: why, note: revokedNote(why) };
|
|
194
|
+
}
|
|
195
|
+
if (r.status === 402) {
|
|
196
|
+
const upgrade = sameOriginLink(body?.upgrade, device.origin, ACCOUNT_UPGRADE);
|
|
197
|
+
return { outcome: 'lapsed', reason: 'licence_required', note: `Your team's plan has ended, so this machine's licence will not be renewed. Choose a plan at ${upgrade}.` };
|
|
198
|
+
}
|
|
199
|
+
return keep(`http-${r.status}`);
|
|
200
|
+
} catch (e) {
|
|
201
|
+
return { outcome: 'kept', reason: e && e.message ? e.message : 'error' };
|
|
202
|
+
}
|
|
203
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bugb-technologies/bravos",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"security",
|