@bugb-technologies/bravos 1.0.3 → 1.2.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.
@@ -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
+ }
@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { buildBanner, buildBriefing, buildSummary, collect, readVersion } from './lib/briefing.mjs';
6
+ import { resolveTheme } from './lib/palette.mjs';
6
7
 
7
8
  const STDIN_WAIT_MS = 1000;
8
9
 
@@ -62,9 +63,11 @@ async function main() {
62
63
  if (env.BRAVOS_BANNER !== 'off' && (source === null || source === 'startup') && harness !== 'agy') {
63
64
  const version = readVersion(dirname(fileURLToPath(import.meta.url)));
64
65
  const color = !env.NO_COLOR && env.BRAVOS_BANNER_COLOR !== 'off';
66
+ // Which palette: BRAVOS_THEME, COLORFGBG, the choice saved by bravos start, else neutral (hooks/lib/palette.mjs).
67
+ const { theme } = resolveTheme(env);
65
68
  // Codex lists a hook's message as a warning, so it gets a three-line summary, not the art.
66
69
  // The leading newline puts the logo on its own lines: Claude Code prefixes the first line with "SessionStart:startup says:".
67
- out.systemMessage = harness === 'codex' ? buildSummary(inputs, { harness, version }) : '\n' + buildBanner(inputs, { harness, version, color });
70
+ out.systemMessage = harness === 'codex' ? buildSummary(inputs, { harness, version }) : '\n' + buildBanner(inputs, { harness, version, color, theme });
68
71
  }
69
72
  } catch (e) {
70
73
  text = `bravos briefing failed: ${e instanceof Error ? e.message : String(e)}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.0.3",
3
+ "version": "1.2.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",
@@ -41,6 +41,8 @@
41
41
  "build:plugin-release": "node scripts/build-plugin-release.mjs"
42
42
  },
43
43
  "dependencies": {
44
+ "@clack/core": "1.5.1",
45
+ "@clack/prompts": "1.8.1",
44
46
  "commander": "^15.0.0",
45
47
  "smol-toml": "^1.9.1"
46
48
  },
@@ -11,12 +11,17 @@ export default function bravos(pi) {
11
11
  pending ??= (async () => {
12
12
  const lib = await import(pathToFileURL(join(cwd, '.bravos', 'hooks', 'lib', 'briefing.mjs')).href);
13
13
  const inputs = await lib.collect(cwd, process.env);
14
+ // The palette for this terminal's background (an older install has no palette.mjs: dark, as before).
15
+ const theme = await import(pathToFileURL(join(cwd, '.bravos', 'hooks', 'lib', 'palette.mjs')).href)
16
+ .then((p) => p.resolveTheme(process.env).theme)
17
+ .catch(() => 'dark');
14
18
  const banner = process.env.BRAVOS_BANNER === 'off'
15
19
  ? null
16
20
  : lib.buildBanner(inputs, {
17
21
  harness: 'omp',
18
22
  version: lib.readVersion(join(cwd, '.bravos', 'hooks')),
19
23
  color: !process.env.NO_COLOR && process.env.BRAVOS_BANNER_COLOR !== 'off',
24
+ theme,
20
25
  });
21
26
  return { briefing: lib.buildBriefing(inputs), banner };
22
27
  })().catch((e) => ({ briefing: `bravos briefing failed: ${e instanceof Error ? e.message : String(e)}`, banner: null }));